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

前端 未结 5 1091
北恋
北恋 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 11:59

    You must almost always use the snippet with finally block when you have resources that needs clean up in both successful or error scenarios. A typical example is the jdbc connection object which should always be closed (clean up) in the finally block.

    0 讨论(0)
  • 2021-02-13 12:07

    Use a finally block if you have code that must execute regardless of whether or not an exception is thrown.

    Cleaning up scarce resources like database connections are a good example.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-13 12:13

    An obvious case is when you re-raise or throw another exception in your catch block.

    0 讨论(0)
  • 2021-02-13 12:24

    Imagine to have a return statement inside the catch block: the C block will not be executed in snippet B, but in snippet A it will, before returning.

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