Difference between try-finally and try-catch

前端 未结 11 566
栀梦
栀梦 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:30

    try {
        statements;
    } catch (exceptionType1 e1) {      // one or multiple
        statements;                 
    } catch (exceptionType2 e2) {
        statements;
    }    
    ...
    } finally {                                 // one or none
        statements;
    }
    
    1. All try statements must include either one catch clause or a finally clause
    2. It can have a multiple catch clauses but only one finally clause
    3. During any execution, if any errors occurs, then the Control is transferred to the appropriate Catch block and executes the statements and Finally block is executed.

    No Matter what The Finally block is always executed, So in General, Finally block is used, when you have sessions, Database connections or Files or sockets are open, then the code for closing those connections will be placed. This is just to make sure in an application no memory leaks or Any other issues should not occur.

提交回复
热议问题