Should unchecked exceptions be caught and dealt with?

后端 未结 6 1533
说谎
说谎 2020-12-17 05:00

I have been reading many posts about exceptions lately and I have a question whether unchecked exceptions should be caught. I have read that if you want your application to

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 05:21

    The basic difference between the Checked and Unchecked Exception is that, you need to explicitly handle the former or propagate it in the inheritance hierarchy, while this is not required for the later.

    Also, CheckedException extend from java.lang.Exception, while UncheckedExceptions extend from java.lang.RuntimeException, which are not needed to be handled. Note that, RuntimeException are themselves a subclass of Exception.

    Given, all the information above, if you handle an unchecked exception then its fine. It will work fine, and the control will go to the corresponding catch block. But you shouldn't do it. Unless, you really need it and you have a proper way to handle them.

    • For e.g: - You should handle an IllegalArgumentException which is an Unchecked Exception.

    • And then, you shouldn't handle errors like: - StackOverflowError. As, you don't know why that problem might have occurred, and what could be an appropriate way to handle it. So, just leave it to the JVM. Errors are Unchecked Exception that you cannot recover from.

    For more details, refer these links: -

    • http://tutorials.jenkov.com/java-exception-handling/checked-or-unchecked-exceptions.html
    • http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

提交回复
热议问题