When to choose checked and unchecked exceptions

前端 未结 18 2926
南方客
南方客 2020-11-22 04:13

In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My inst

18条回答
  •  天命终不由人
    2020-11-22 05:00

    It's not just a matter of the ability to recover from the exception. What matter most, in my opinion, is whether the caller is interested in catching the exception or not.

    If you write a library to be used elsewhere, or a lower-level layer in your application, ask yourself if the caller is interested in catching (knowing about) your exception. If he is not, then use an unchecked exception, so you don't burden him unnecessarily.

    This is the philosophy used by many frameworks. Spring and hibernate, in particularly, come to mind - they convert known checked exception to unchecked exception precisely because checked exceptions are overused in Java. One example that I can think of is the JSONException from json.org, which is a checked exception and is mostly annoying - it should be unchecked, but the developer simply haven't thought it through.

    By the way, most of the time the caller's interest in the exception is directly correlated to the ability to recover from the exception, but that is not always the case.

提交回复
热议问题