finally in exception handling

后端 未结 8 1723
甜味超标
甜味超标 2021-01-18 17:08

What exactly does a finally block in exception handling perform?

8条回答
  •  一个人的身影
    2021-01-18 17:41

    Though there are many answers have already given that finally block is required to execute some piece of code in all the conditions whether there is some interruption due to exception, or some bad code, or you return the program control flow from try block, Here I'm adding an example to explain the need of finally block;

    Let's suppose you have borrowed a pen from your friend. You use it and then return ( I consider you a gentleman). Now whatever happens, you have to return the pen. You can handle various situations and you put most unavoidable condition in finally block.

    //Borrow the pen
    try{
      //Use the pen
    }catch(StolenPen how){
      //Buy new pen
    }catch(InkFinished how){
      //Refill the pen
    }catch(SomethingWrong how){
      //Buy new pen
    }finally{
      //Return new pen
    }
    

提交回复
热议问题