posted 7 years ago
Hello guys
I'm finishing the study guide, and the last chapter is about Exceptions. It is a really peaceful chapter, there is not a lot of things to know about Exceptions for the OCA Exam.
Although it is one of the easiest chapters of the book, there is something that I've read and never paid attention before. It is about throwing an exception in the finally block.
I know that the finally block will always be executed (ok, not always, there is an exception for this rule, right?). What I mean is, the finally will be executed if the try block executes perfectly as well as if it throws an exception that is caught by the catch, even if there is a return statement inside the catch block (the finally is executed and then the return).
That's ok, but let's take a look at the following code:
When executing the previous code, the exception is thrown following the stack with the methods, starting from doSomething(), then start() and then main(). Ok, but where I marked with "1", the try block throws the Exception, and then the catch block catches this exception. But the catch block throws an exception too, and then the finally block executes and throws another exception, and the result is that the exception thrown by the finally is considered, while the exception thrown by the catch block is forgotten.
So, I understand that the last thrown exception is always the one that is considered.
The book says the following: "This is why you often see another try/catch inside a finally block - to make sure it doesn't mask the exception from the catch block". I didn't understand this sentence. What "mask the exception from the catch block" means? Could anyone give me an example?
Thank you.