How does one decide to create a checked excpetion or an unchecked exception [duplicate]

时间秒杀一切 提交于 2019-12-02 12:27:41

There might be different opinions but I'd say the difference is how the caller should handle that exception:

  • If you want to make sure the caller handles the exception either by doing something (logging, trying to recover etc.) or rethrowing then use a checked exception. An example would be said ValidationException: if the data is invalid the caller should have to handle that, e.g. by telling someone to fix the data or by trying something else. (Note that there may be unchecked validation exceptions such as javax.validation.ValidationException. There can be various reasons for making those unchecked, e.g. if a framework doesn't allow/support checked exceptions or if some central handler will catch them anyway so the developer doesn't have to bother.)
  • It you don't want to force the caller to handle exceptions that normally should not be thrown (e.g. programming errors etc.) use an unchecked exception. An example for this might be the always dreaded NullPointerException: it should not happen that something you want to use is null so it might be considered a programming error. If something could be null but should not you might want use a checked exception instead.

    Note that some libraries/methods use IllegalArgumentException which is an unchecked exception. If this exception is thrown there's normally a programming error in that the contract of a method (e.g. the parameter value must not be negative) is violated and that the caller should fix the code or do some checks himself.

Another point of view might be: is the exception expected to be thrown in some cases or not? Expected exceptions (that still mean some kind of error happened) would be checked exceptions since that way you'd communicate to the caller that he should expect those exceptions being thrown in some cases (e.g. if the data is invalid). If the exception is unexpected you should not force the caller to handle such an exception since you'd not expect it to be thrown at all - thus it would be an unchecked exception.

As per Joshua Bloch, Book Effective Java, Item 58 summarizing it in a single line. Thumb rule is Use checked exceptions for recoverable conditions and runtime exceptions for programming errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!