What will happen if you put the return statement or System.exit () on the try or catch block? Will finally block execute?

By | March 7, 2023

If a return statement or System.exit() call is present inside the try or catch block, the control will immediately exit from the method or program and the finally block will execute before the method or program terminates.

In the case of a return statement, the finally block will execute before the value is actually returned from the method. This can be useful if there are resources that need to be cleaned up before the method returns, regardless of whether an exception was thrown or not.

Similarly, if a System.exit() call is made inside the try or catch block, the finally block will execute before the program terminates. However, since System.exit() terminates the entire program, the finally block will be the last thing to execute before the program terminates, and any code after the System.exit() call will not be executed.

It’s important to note that the behavior of finally block execution is not affected by the presence of return or System.exit() statements inside the try or catch blocks. The finally block will always execute, regardless of whether an exception was thrown, a return statement was encountered, or a System.exit() call was made.

Leave a Reply

Your email address will not be published. Required fields are marked *