can't java unchecked exceptions be handled using try/catch block?

后端 未结 8 1924
旧时难觅i
旧时难觅i 2020-12-24 02:29

In a tutorial I found that Unchecked Exception can\'t be handled by your code i.e. we can\'t use try/catch block and the examples are exception

8条回答
  •  借酒劲吻你
    2020-12-24 03:02

    All the unchecked exceptions can be treated in the same way as the checked ones - if you want, you can let them pass by declaring that the method throws them:

    public void m() throws RuntimeException {}
    

    Or you can catch them:

    public void m() {
        try {
            // some code
        } catch (RuntimeException re) {
            // do something
        }
    }
    

    It should be noticed, the class RuntimeException acts as a catch-all for the unchecked exceptions (since all the unchecked exceptions extend from it), much in the same way that the Exception class is the catch-all for checked exceptions.

    As has been mentioned before, the only real difference is that for checked exceptions you have to handle them (by letting them pass or catching them) and the compiler will make sure of it - on the other hand, the handling of unchecked exceptions is optional.

    It all boils down to the expected usage of each exception type - you're supposed do be able to recover from checked exceptions (or at least do something about them, when they occur), whilst for unchecked exceptions, there might not be a reasonable way to recover from them. This of course, is a bit subjective.

提交回复
热议问题