What happens if both catch and finally blocks throw exception?
Answer: No. You cannot throw the exception and also catch it in the same method. The exception that is declared using throws is to be handled in the calling method that calls the method that has thrown the exception.
When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.
The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.
Java try, catch and finally blocks helps in writing the application code which may throw exceptions in runtime and gives us a chance to either recover from exception by executing alternate application logic or handle the exception gracefully to report back to the user.
When the finally
block throws an exception, it will effectively hide the exception thrown from the catch
block and will be the one ultimately thrown. It is therefore important to either log exceptions when caught, or make sure that the finally block does not itself throw an exception, otherwise you can get exceptions being thrown that are stifled and never seen.
When catch throws an exception, finally block will be run and then exit with an exception. If the finally block throws an exception, the block will exit with an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With