Difference between try-finally and try-catch

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

    try is used to run a method that may throw an exception

    catch is used to "catch" stop that exception

    finally is used for any clean up needed from that exception being caught or not

    try{
        myObject.riskyMethod(); // run a method that may throw an exception
    }
    catch(Exception ex){
        myLogger.log(ex.Message); // "catch" stop that exception
    }
    finally{
        myObject = null; // clean up needed from that exception being caught
    }
    

提交回复
热议问题