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

后端 未结 8 1917
旧时难觅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:09

    They can be handled, but you don't have to. If you don't handle them, they will propagate and climb up the calling methods stack, until one of them catches it. If none does, the program will crash.

    Usually, the bottom line is that if a client can reasonably be expected to recover from an exception, then it should be a checked exception. If a client cannot do anything to recover from the exception, then it's ok to have it as an unchecked exception.

    Also, checked exceptions are useful to document an API that you expect to be used by 3rd-parties. When they know your method can throw a specific exception, they will code accordingly and handle the case. If you only use unchecked exceptions, all bets are off.

    A common pattern (some people don't like it, but in some cases it's ok when you know what you're doing) is to wrap thrown checked exceptions into unchecked ones.

    try {
       ... code that can throw CheckedException ...
    } catch (CheckedException oopsSomethingBadHappened) {
        throw new RuntimeException("Something bad happened!", oopsSomethingBadHappened);
    }
    

提交回复
热议问题