Campbell Ritchie wrote:Yes, I can see the problem now; thank you for explaining it. You are lucky that you are unlikely to repeat that mistake.
Campbell Ritchie wrote:Well done
But what was the problem?
That would be the wrong conclusion. Go through the tutorials and understand what each kind of exception (checked vs. unchecked) is for. It's quite appropriate to allow unchecked exceptions to blow up and interrupt program execution while you're still developing and testing your program. In this case, you want that to happen because it allows you to find developer mistakes and fix them. As for checked exceptions, it may be appropriate to allow them to bubble up to a level where the decision on how to handle them makes sense. It all depends on the context.
Campbell Ritchie wrote:That is an unchecked exception. The compiler will allow it to compile without needing a catch, and the finally will be executed. I suggest you go through this part of the Java™ Tutorials.
Junilu Lacar wrote:
Eric Kaiser wrote:"If you define a try block, you can pair it with a matching catch or finally block, or both."
So by this I understand you don't have to handle the exception if it arises or not, finally() block will always run.
It's not a question of whether or not the finally block will run. What you got there was a compile-time error because of the rule that checked exceptions must be either declared with throws or caught in a catch() block. Since you did neither, then the code will not compile. The presence or absence of a finally block is irrelevant.
Dave Tolls wrote:MyEx extends Exception, which means that it needs to be handled (as the compiler error says).
It can be handled either by catching it in a catch block, or by changing the method signature to show that it throws the exception.
Your second code works because you have told Java that the exception is being passed out of the method rather than being handled inside the method, by changing the signature to note the exception thrown.