Is it valid to have finally block without try and catch?

前端 未结 11 1579
遇见更好的自我
遇见更好的自我 2021-02-04 01:32

I am trying to use the finally block without using the try/catch blocks but getting the error in Eclipse.

Can I use the finally block without using the try/catch blocks?

11条回答
  •  星月不相逢
    2021-02-04 02:06

    You must have a try block with a finally block. The try block defines which lines of code will be followed by the finally code. If an exception is thrown prior to the try block, the finally code will not execute.

    Adding catch blocks is optional:

    try {
    
      // something
    
    } finally {
      // guaranteed to run if execution enters the try block
    }
    

提交回复
热议问题