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

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

    No you can't

    you can use Try-catch-finally or try-finally

     try {
    
        }catch (Exception e){
    
        }
        finally{
    
        }
    

    or

    try {
    
        }
        finally{
    
        }
    
    0 讨论(0)
  • 2021-02-04 02:19

    finally should have atleast a try block, catch is optional. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. As per the JLS

    A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.

    Hence a finally should always be preceded by a try block.

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

    The finally block always executes when the try block exits. So you can use finally without catch but you must use try.

    For more details check doc here

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

    If an exception is thrown prior to the try block, the finally code will not execute. The finally block always executes when the try block exits. So you can use finally without catch but you must use try.

    0 讨论(0)
  • 2021-02-04 02:22
    • Using only try block is not correct.
    • Try block can be used with only one block from catch or finally block.
    • You can use try block with catch and finally.If you use finally block with try block then catch block become optional.
    0 讨论(0)
提交回复
热议问题