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

前端 未结 11 1557
遇见更好的自我
遇见更好的自我 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:00
    • A try statement should have either catch block or finally block, it can have both blocks.

    • We can’t write any code between try-catch-finally block.

    • We can’t have catch or finally clause without a try statement.

    • We can have multiple catch blocks with a single try statement.try-catch blocks can be nested similar to if-else statements.

    • We can have only one finally block with a try-catch statement.

    0 讨论(0)
  • 2021-02-04 02:01

    From Oracle Trails:

    The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

    From the above statement, you cannot have finally block alone on its own. below are the combinations allowed.

    1. try catch finally

    2. try catch

    3. try finally

    0 讨论(0)
  • 2021-02-04 02:04
    try {
        // Block of code with multiple exit points
    }
    finally {
        // Block of code that must always be executed when the try block
        // is exited, no matter how the try block is exited
    }
    
    0 讨论(0)
  • 2021-02-04 02:05

    The code within the finally block is guaranteed to execute if program control flow enters the corresponding try block. So it makes no sense to have a finally without a try.

    The only exception to this is if the program encounters a System.exit(...) call before the finally block, as that shuts down the virtual machine.

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

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