Why do we use finally blocks?

2019-01-07 05:11发布

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 { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }

Code B:

try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code

9条回答
迷人小祖宗
2楼-- · 2019-01-07 05:44

If catch block throws any exception then remaining code will not executed hence we have to write finaly block.

查看更多
Anthone
3楼-- · 2019-01-07 05:52

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.

查看更多
小情绪 Triste *
4楼-- · 2019-01-07 05:58

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();
}
查看更多
登录 后发表回答