Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if both catch and finally blocks throw exception?

What happens if both catch and finally blocks throw exception?

like image 773
Arthur Avatar asked Sep 26 '09 23:09

Arthur


People also ask

Can you throw an exception from a catch or a finally block?

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.

What will happen when catch and finally block both return value?

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

What if finally block throws an exception?

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.

How do both catch and finally work in an exception program?

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.


2 Answers

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.

like image 200
adrianbanks Avatar answered Oct 06 '22 00:10

adrianbanks


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.

like image 25
NawaMan Avatar answered Oct 06 '22 00:10

NawaMan