Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if catch block or finally block having some exception? [duplicate]

In exception handling, what will happen if catch block or finally block having Exception?

like image 967
Tilak Raj Avatar asked Feb 13 '14 09:02

Tilak Raj


People also ask

What happens if exception thrown in catch block finally?

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.

What will happen when catch and finally block both?

When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.

Can you catch exception twice?

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 | .

Can we catch 2 exceptions in single catch block?

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.


2 Answers

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

like image 79
Abimaran Kugathasan Avatar answered Oct 23 '22 20:10

Abimaran Kugathasan


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

like image 26
Zeeshan Avatar answered Oct 23 '22 19:10

Zeeshan