Why do we use finally blocks?

前端 未结 11 2341
甜味超标
甜味超标 2020-11-27 11:43

As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?

Code A:

try { /*          


        
11条回答
  •  误落风尘
    2020-11-27 12:17

    You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.

    Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.

    For example:

    conn c1 = new connection();
    try {
        c1.dosomething();
    } catch (ExceptionA exa) {
        handleexA();
        //c1.close();
    } catch (ExceptionB exb) {
        handleexB();
        //c1.close();
    } finally {
        c1.close();
    }
    

提交回复
热议问题