Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does finally always get called? [duplicate]

Tags:

java

Possible Duplicate:
In Java, does return trump finally?

What does this function return?

public int wasExceptionThrown() {
   try {
     if(1==1)
        throw new RuntimeException();
     return 1;
   } catch(Exception e) {
     return 2;
   } finally {
     return 3;
   }
   return 0;
}
like image 256
Paul Nikonowicz Avatar asked Jan 08 '13 16:01

Paul Nikonowicz


People also ask

Is finally always called?

Because a finally block will always be called unless you call System.

Is finally block always called?

A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.

Does finally get called after return?

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.

Is finally always called C#?

It is a reserved keyword in C#. The finally block will execute when the try/catch block leaves the execution, no matter what condition cause it. It always executes whether the try block terminates normally or terminates due to an exception. The main purpose of finally block is to release the system resources.


1 Answers

If you call System.exit(0); then finally blocks are not called as the thread is shutdown immediately. In all other cases finally is called when the block exits (assuming it does)

like image 57
Peter Lawrey Avatar answered Sep 28 '22 09:09

Peter Lawrey