Why do we use finally blocks?

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

    Finally always gets executed, where as your code after the catch may not.

    0 讨论(0)
  • 2020-11-27 12:14

    Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-11-27 12:15

    Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...

    Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.

    In some cases finally won't execute such as JVM Fail, Thread terminate, etc.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-11-27 12:21

    finally ALWAYS executes, unless the JVM was shut down, finally just provides a method to put the cleanup code in one place.

    It would be too tedious if you had to put the clean up code in each of the catch blocks.

    0 讨论(0)
提交回复
热议问题