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

前端 未结 11 1558
遇见更好的自我
遇见更好的自我 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:12

    The reason why you cannot have a finally without a try is because you could have multiple finally statements in the same scope and the try indicates what block of code the finally pertains to in case an error occurs.

    Another interesting feature of the finally is that it must execute no matter what when the try is entered. For example what if you use a goto to skip over your finally statement? If the goto is inside of the try it will execute the finally statement however if the goto is above/outside the try statement then it will skip the finally code. finally is relevant only to the code that is surrounded in the try. If you have no try then the finally is not relevant to anything.

提交回复
热议问题