Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `finally` block executed in case there is `return` inside a `try` or a `catch` block?

Using a try-catch-finally construction to retrieve a database record, it seems that I need to return a value inside a try block in case everything was fine (as in case of an exception the end of the function is not meant to be reached). But If I return inside try, is finally code going to be reached (to close the connection etc.)?

like image 223
Ivan Avatar asked Oct 19 '11 02:10

Ivan


People also ask

Is the finally block executed when there is a return within the try block?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

Can we use return statement in try catch or finally block?

Yes, we can write a return statement of the method in catch and finally block.

In which case finally block is executed?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Can you have a return in a try catch?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.


1 Answers

Yes,

The result of the try/catch expression will be the last line of either the try or catch block, but the finally block will always execute no matter what

like image 193
Pablo Fernandez Avatar answered Oct 27 '22 09:10

Pablo Fernandez