Does the finally block always run in Java?

I have a try / catch with a return inside. Will the finally block be executed?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("No se si esto se va a imprimir.");
}

I know I can write this and see what happens (which is really what I'm going to do) but when I Googled it, nothing showed up, so I asked the question here.

This is a question translated from the original in English and adapted to the results it gives on my computer: does finally always execute in Java? by jonny five

 28
Author: Comunidad, 2015-12-01

4 answers

Finally will be called.

The only times that finally will not execute will be when:

  1. if you call System.exit () or
  2. if the jvm crashes first

This answer is a translation of the English original of jodonnell

Edited 12/2/15: taking into account Does the finally block execute if the thread running the function is interrupted? by Subhrajyoti Majumder

 26
Author: Perdomoff, 2017-05-23 12:39:21

A very simple question based on java principles, The Block finally will always be called.

try {
    //Declaraciones que pueden causar una excepción.
}
catch {
   //Manejo de excepción.
}
finally {
   //Declaraciones a ser ejecutadas
}

As long as AS commented, You end the execution of the code or there are errors.

More information :The Finally Block

 7
Author: Jorgesys, 2017-12-19 17:10:03

NOT ALWAYS

The Java language specification describes how the try-catch-finally and try-finally blocks work in the Section 14.20.2.
Nowhere does it specify that finally always runs.
But it does specify that for all cases where the try-catch-finally or try-finally block is completed earlier the finally block must have been executed.

I.e.. If SIG is what will be executed after the try-catch-finally block or try-finally and End is what's inside finally, the JLS guarantees that End is always executed before SIG is executed.

Why does the JLS not guarantee that the finally block is always executed after the try block? Because it's impossible. It is unlikely but possible that the virtual machine will be aborted (kill, crash, shut down computer) just after the try Block ends and before the finally block is executed. And there is nothing that can be do from the language specification to avoid this.

 4
Author: Anonymous Coward, 2015-12-19 14:12:24

Within a block try / catch finally it always runs, as the Java documentation says :

The finally block is always executed when the try block exits. This ensures that the finally Block is executed even if a unexpected exception. But, finally, it is useful for something more than the exception handling: allows the programmer to prevent the code from cleaning is accidentally diverted by a return, a continuation or a disruption. put cleanup code in a block finally is always good practice , even when not foreseen exemption.

enter the description of the image here

Note: If the JVM exits while the try or catch code is running, then the finally block cannot be executed. Similarly, if the thread executing the code try or catch is interrupted or deleted, the finally block cannot run even though the application in its set continue .

From Java SE 7 'finally' lost prominence

Prior to Java SE 7, the use of finally could be implemented as a key tool to prevent resource leakage . When closing a file or recovering resources, it was recommended to place the code in a finally Block to ensure that the resource will always be recovered or closed.

Since finally is always executed, regardless of whether the try statement is complete normally or abruptly, finally was the only possible option to ensure that a resource would be finally closed.

We see this in the following example:

//Otro uso de finally antes de Java SE 7
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

Before Java 7 finally it helped us to leave the ground clean of all open resources.

From Java 7 the try-with-resources statement

The judgment try-with-resources it is a try statement declaring one or more resources. a resource is an object that must be closed after the program ends. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects that implement java.io.Closeable, can be used as a resource.

The following example reads the first line of a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The statement statement appears in parentheses immediately after the Keyword try. The BufferedReader class, in Java SE 7 and later, implements the java.lang.AutoCloseable interface. Since instance BufferedReader is declared in a judgment try-with-resources, it will close regardless of whether the try statement completes normally or abruptly (as a result of the BufferedReader.readLine method that throw a IOException).

 -1
Author: A. Cedano, 2017-03-18 03:45:48