Is the Finally block always run in Java?

Asked

Viewed 4,676 times

9

In this code there is a block of Try/catch with a Return within 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");
}

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

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

3 answers

15


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

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

The only moments when the finally will not be called healthy:

  1. If you call System.exit() or
  2. another thread interrupt the current (through the method interrupt()) or
  3. If the JVM gives crash before.

According to the tutorials from Oracle:

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.

(Response based on question 1 and question 2 of Stackoverflow in English).

6

Yes, he will always be executed!

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

Why does this happen?

The block finally, generally, it is used to close connections, files and release resources used within the block try/catch. As it is always run, we can ensure that always after a resource is used within the try/catch it may be closed/released on finally.

5

Yes. The Finally block will always run even if it falls in the 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 I helped, hugs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.