When should I use the finally-block in Java's try-catch-finally

前端 未结 5 1085
北恋
北恋 2021-02-13 11:39

When should I use code snippet A instead of snippet B (i.e. what are the benefits of using snippet A)?:

Snippet A:

try {
    // codebloc         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 12:10

    It's useful if you need to do some cleanup, e.g. close a database connection. Because "finally" is executed always, you don't need to do the bug-prone copy-paste of the same code in the end of the "try" and in also in one or more "catch" blocks.

提交回复
热议问题