In exception handling, what will happen if catch block or finally block having Exception?
Q #3) What happens when a catch block throws an exception? Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.
When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.
In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe | .
Handling More Than One Type of Exception In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Finally block exception will mask the original exception.
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagates outward.
Check here and here for more details
As per the JLS 14.20.2. Execution of try-finally and try-catch-finally
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
A finally block may throw an exception and if so, any exception thrown by the try or catch block is lost.
Ref: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
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