Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-catch-finally in java

In Java, will the finally block not get executed if we insert a return statement inside the try block of a try-catch-finally ?

like image 448
Nikhil Avatar asked Aug 22 '11 06:08

Nikhil


People also ask

What is try catch finally in Java?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.

Does Java have try catch finally?

Q #4) What is try-catch-finally in Java? Answer: The try-catch-finally block contains the three blocks i.e. try block, catch block, and finally block. Try block contains the code that might throw an exception. Catch block contains the exception handler for exceptions in the try block.

Can we use try catch and finally?

Yes, it is different. Finally will always run (barring program crash). If the function exits inside of the try catch block, or another error is thrown in either the try or the catch, the finally will still execute. You won't get that functionality not using the finally statement.

Can we write try catch in finally block?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.


1 Answers

The only time a finally block will not be executed is when you call exit() before finally is reached. The exit() call will shutdown the JVM, so no subsequent line of code will be run.

EDIT: This is not entirely correct. See the comments below for additional information.

like image 187
Gabriel Negut Avatar answered Sep 24 '22 08:09

Gabriel Negut