Is the finally block always executed in Java? [duplicate]

8

In this code there is a try / catch block with a return inside it.

try {  
    alguma_coisa();  
    return successo;  
}  
catch (Exception e) {   
    return falha;  
}  
finally {  
    System.out.println("Eu não sei se será possível printar esta mensagem");
}

Turning this code would be simple, but the idea of the question is:

Not only on this occasion, but will the finally block always be called in Java?

    
asked by anonymous 24.08.2015 / 22:18

3 answers

13

The block finally will always be executed, except in rare situations.

In general, it is a guarantee that your code will free busy resources even if exceptions occur ( Exceptions ) or the method containing try returns prematurely ( return ).

The only times that finally will not be called are:

  • If you call System.exit() or
  • another thread interrupt the current one (via the interrupt() method) or
  • If the JVM crash before.
  • According to Oracle Tutorials :

      

    If the JVM exits while the try or catch code is being executed,   then the finally block may not execute. Likewise, if the thread   executing the try or catch code is interrupted or killed, the finally   block may not execute even though the application as a whole continues.

    (Answer based on question 1 and StackOverflow question 2 .

        
    24.08.2015 / 22:26
    7

    Yes, it will always run!

    The finally block is used to ensure that a code runs after a try , even though an exception has been generated . Even if you have a return in try or catch , the finally block is always executed .

    For what reason does this happen?

    The finally block is generally used to close connections, files, and free resources used within the try/catch block. Since it is always executed, we can ensure that whenever a resource is used within try/catch it can be closed / released in finally .

        
    24.08.2015 / 22:29
    5

    Yes. The Finally block will always run even if it falls into catch.

    Take this test:

        public class Teste {
    
        public static void main(String[] args){
    
        try {  
            int a = 0;
            int b = 0;
            int res = a/b;
            System.out.println(res);
        }  
        catch (Exception e) {   
            System.out.println("Erro.");  
        }  
        finally {  
            System.out.println("Finally");
        }
    
        }
    
        }
    

    Note that this algorithm will generate an exception because it is not possible to divide 0 by 0. Then it will generate an exception and fall into the finally block. Hope to have helped, hugs.

        
    24.08.2015 / 22:25