Difference between try-finally and try-catch

前端 未结 11 558
栀梦
栀梦 2020-12-23 03:05

What\'s the difference between

try {
    fooBar();
} finally {
    barFoo();
}

and

try {
  fooBar();
} catch(Throwable thro         


        
11条回答
  •  庸人自扰
    2020-12-23 03:09

    These are two different things:

    • The catch block is only executed if an exception is thrown in the try block.
    • The finally block is executed always after the try(-catch) block, if an exception is thrown or not.

    In your example you haven't shown the third possible construct:

    try {
        // try to execute this statements...
    }
    catch( SpecificException e ) {
        // if a specific exception was thrown, handle it here
    }
    // ... more catches for specific exceptions can come here
    catch( Exception e ) {
        // if a more general exception was thrown, handle it here
    }
    finally {
        // here you can clean things up afterwards
    }
    

    And, like @codeca says in his comment, there is no way to access the exception inside the finally block, because the finally block is executed even if there is no exception.

    Of course you could declare a variable that holds the exception outside of your block and assign a value inside the catch block. Afterwards you can access this variable inside your finally block.

    Throwable throwable = null;
    try {
        // do some stuff
    }
    catch( Throwable e ) {
        throwable = e;
    }
    finally {
        if( throwable != null ) {
            // handle it
        }
    }
    

提交回复
热议问题