Does the finally block always run in Java?

22

I have a try / catch with a return inside. Will the block finally 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 looked for it in google, nothing appeared, 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? from jonny five

    
asked by Perdomoff 01.12.2015 в 23:07
source

4 answers

24

finally will be called.

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

  • if you call System.exit () or
  • if the jvm has a failure first (crashes)
  • This response is a translation from the original in English from jodonnell

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

        
    answered by 01.12.2015 / 23:07
    source
    7

    A very simple question based on the principles of java, the finally block 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 you comment, you finish the execution of the code or there are errors.

    More information: The Finally Block

        
    answered by 01.12.2015 в 23:29
    3

    NOT ALWAYS

    The Java language specification describes how the try-catch-finally and try-finally blocks work in 14.20.2 .
    Nowhere does it specify that finally it is always executed.
    But it does specify that for all cases in which the try-catch-finally or try-finally block is completed before the finally block has to be executed.

    That is to say. If SIG is what will be executed after the try-catch-finally or try-finally block and FIN is what is inside finally, the JLS guarantees that FIN is always executed before SIG is executed.

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

        
    answered by 12.12.2015 в 15:16
    -1

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

      

    The finally block is always executed when the block try comes out. This   guarantees 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 an interruption. Put cleaning code in a block    finally is always a good practice , even when not foreseen   exceptions.

    Note: If the JVM exits while the try or catch code is running, then the finally block can not be executed . Likewise, if the thread that executes the code try or catch is interrupted or deleted, the finally block can not be executed even if the application as a whole continues .

    From Java SE 7 'finally' lost prominence

    Before Java SE 7 you could implement the use of finally as a key tool to avoid resource leakage . When closing a file or recovering resources, it was recommended to place the code in a finally block to make sure that the resource will always recover or close.

    Since finally is always executed, regardless of whether the try instruction completes 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 helped us to leave the land clean of all open resources.

    As of Java 7, the try-with-resources Statement

    was implemented

    The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the end of the program . 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 the objects that implement java.io.Closeable , can be used as a resource.

    The following example reads the first line of a file. Uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the end of 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 declaration statement appears in parentheses immediately after keyword try . The class BufferedReader , in Java SE 7 and later, implements the interface java.lang.AutoCloseable . Since instance BufferedReader is declared in a try-with-resources statement, will be closed regardless of whether the try statement completes normally or abruptly (as a result of the BufferedReader.readLine method that throws a IOException ).

        
    answered by 18.03.2017 в 03:36