Put method return before a "finally" block

3

Considering:

try {
    System.out.println("Parte 1");
    return false;
} finally {
    System.out.println("Parte 2");
}

What will be the output and what happens underneath the cloths so that the output goes out like this?

    
asked by anonymous 29.11.2014 / 01:35

2 answers

8

The intent of finally is to ensure that this block is executed under any circumstances (unless every platform has some catastrophic, of course, or System.exit() behavior). So no matter what happens in the method, it will run. It does not matter if it goes out with return or throw .

Then the output will be:

Parte 1
Parte 2

See working on ideone .

Documentation .

Rewriting

This block is rewritten by the compiler (it's something like this, in C # it's so). It would look something like this:

try {
    System.out.println("Parte 1");
} finally {
    System.out.println("Parte 2");
}
return false;

Now

try {
    System.out.println("Parte 1");
    return false;
} finally {
    System.out.println("Parte 2");
    return true;
}

Will be transformed into:

try {
    System.out.println("Parte 1");
} finally {
    System.out.println("Parte 2");
}
return true;

I placed GitHub for future reference .

Note that executing a finally takes precedence when the statements are conflicting. If there is return within catch , it will precede return of try but will lose finally .

Conclusion

In any case there is the guarantee of execution. The actual implementation is not important since it could change. The important thing is to know that is guaranteed to run block finally before exiting the method , so before return of try . Of course if there is any expression in return it will be saved in temporary variable to avoid execution at the wrong time in reordering instructions.

    
29.11.2014 / 01:48
5

The output will be:

Parte 1
Parte 2

And then false will be returned.

The finally block runs whenever the try block ends, even if it has thrown an exception, returned, aborted a loop, or anything like that.

Internally, the JVM saves the returned value to a local variable that it invents for it, runs finally and then returns the value of the local variable. It does the same for exceptions.

    
29.11.2014 / 01:46