When to choose checked and unchecked exceptions

前端 未结 18 2892
南方客
南方客 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:03

    I agree with the preference for unchecked exceptions as a rule, especially when designing an API. The caller can always choose to catch a documented, unchecked exception. You're just not needlessly forcing the caller to.

    I find checked exceptions useful at the lower-level, as implementation detail. It often seems like a better flow of control mechanism than having to manage a specified error "return code". It can sometimes help see the impact of an idea for a low level code change too... declare a checked exception downstream and see who would need to adjust. This last point doesn't apply if there are a lot of generic: catch(Exception e) or throws Exception which is usually not too well-thought out anyway.

提交回复
热议问题