Why do we use finally blocks?

前端 未结 11 2324
甜味超标
甜味超标 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:15

    Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:

    InputStream in = new FileInputStream("somefile.xyz");
    try {
        somethingThatMightThrowAnException();
    }
    finally {
        // cleanup here
        in.close();
    }
    

提交回复
热议问题