try catch finally question

前端 未结 5 858
你的背包
你的背包 2020-11-29 08:34

In a Try Catch Finally block, does the finally block always execute no matter what, or only if the catch block does not return an error?

I was under the impression

5条回答
  •  长情又很酷
    2020-11-29 08:56

    Not only will a finally block execute following a catch block, try does not even require that any exception be caught for the finally to execute. The following is perfectly legal code:

    try 
    {
    //do stuff
    }
    finally 
    {
       //clean up
    }
    

    I actually took out the catch blocks in some code I inherited when the catch block consisted of:

    catch(Exception ex)
    {
       throw ex;
    }
    

    In that case, all that was required was to clean up, so I left it with just a try{} and finally{} block and let exceptions bubble up with their stack trace intact.

提交回复
热议问题