Does a finally block always get executed in Java?

前端 未结 30 1416
逝去的感伤
逝去的感伤 2020-11-21 07:24

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try         


        
相关标签:
30条回答
  • 2020-11-21 07:26

    Concisely, in the official Java Documentation (Click here), it is written that -

    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.

    0 讨论(0)
  • 2020-11-21 07:26

    Yes, finally block is always execute. Most of developer use this block the closing the database connection, resultset object, statement object and also uses into the java hibernate to rollback the transaction.

    0 讨论(0)
  • 2020-11-21 07:26

    finally will execute and that is for sure.

    finally will not execute in below cases:

    case 1 :

    When you are executing System.exit().

    case 2 :

    When your JVM / Thread crashes.

    case 3 :

    When your execution is stopped in between manually.

    0 讨论(0)
  • 2020-11-21 07:27

    Example code:

    public static void main(String[] args) {
        System.out.println(Test.test());
    }
    
    public static int test() {
        try {
            return 0;
        }
        finally {
            System.out.println("finally trumps return.");
        }
    }
    

    Output:

    finally trumps return. 
    0
    
    0 讨论(0)
  • 2020-11-21 07:27

    That is the whole idea of a finally block. It lets you make sure you do cleanups that might otherwise be skipped because you return, among other things, of course.

    Finally gets called regardless of what happens in the try block (unless you call System.exit(int) or the Java Virtual Machine kicks out for some other reason).

    0 讨论(0)
  • 2020-11-21 07:27

    A logical way to think about this is:

    1. Code placed in a finally block must be executed whatever occurs within the try block
    2. So if code in the try block tries to return a value or throw an exception the item is placed 'on the shelf' till the finally block can execute
    3. Because code in the finally block has (by definition) a high priority it can return or throw whatever it likes. In which case anything left 'on the shelf' is discarded.
    4. The only exception to this is if the VM shuts down completely during the try block e.g. by 'System.exit'
    0 讨论(0)
提交回复
热议问题