Java Try Catch Finally blocks without Catch

后端 未结 11 758
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 20:38

I\'m reviewing some new code. The program has a try and a finally block only. Since the catch block is excluded, how does the try block work if it encounters an exception

相关标签:
11条回答
  • 2020-11-28 21:23

    Inside try block we write codes that can throw an exception. The catch block is where we handle the exception. The finally block is always executed no matter whether exception occurs or not.

    Now if we have try-finally block instead of try-catch-finally block then the exception will not be handled and after the try block instead of control going to catch block it will go to finally block. We can use try-finally block when we want to do nothing with the exception.

    0 讨论(0)
  • 2020-11-28 21:23

    Regardless of exception thrown or not in try block - finally block will be executed. Exception would not be caught.

    0 讨论(0)
  • 2020-11-28 21:24

    If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.

    The finally block is always executed, whether an exception is thrown or not.

    0 讨论(0)
  • 2020-11-28 21:26

    Don't you try it with that program? It'll goto finally block and executing the finally block, but, the exception won't be handled. But, that exception can be overruled in the finally block!

    0 讨论(0)
  • 2020-11-28 21:27

    A small note on try/finally: The finally will always execute unless

    • System.exit() is called.
    • The JVM crashes.
    • The try{} block never ends (e.g. endless loop).
    0 讨论(0)
提交回复
热议问题