How and where do you define your own Exception hie

2020-02-23 05:32发布

How and where do you define your own Exception hierarchy in Java?

My main question concerns package location where your Exception classes must be defined.

Do we create a special package for our exceptions and put all classes inside it?

4条回答
▲ chillily
2楼-- · 2020-02-23 05:55

You can create your Exception classes wherever you want.

The important thing is to extend an existing Exception class (java.lang.Throwable in fact). For instance java.lang.Exception or java.lang.RuntimeException. The first is a checked exception while extending RuntimeException will result in an unchecked exception; the differences between the two are detailed here.

查看更多
你好瞎i
3楼-- · 2020-02-23 06:00

I put all of my custom exceptions into a com.company.project.exception package. I do this rather than putting them "close" to the locations where they crop up.

Here's my reasoning: If a given exception is only cropping up within one or two service classes somewhere, it may not be a general enough exception to deserve its own class. Only if I see a common theme popping up in multiple places will I go to the trouble of creating a custom Exception class. And if it is popping up in multiple places, then there's no logical package to "attach" it to, so an exception-specific package seems like the right way to go.

查看更多
smile是对你的礼貌
4楼-- · 2020-02-23 06:06

The language does not specify any requirements for what packages user-defined Exception classes should be put in. As long as the class extends java.lang.Throwable, it can be thrown.

查看更多
疯言疯语
5楼-- · 2020-02-23 06:08

I use this as a general rule.

  • Where it makes sense, use a pre-defined Java exception. For example, if your code has some sort of I/O Error, it is fine to throw an IOException.
  • Only use exception hierarchies if you need to differentiate between the two exceptions in a try/catch block. A lot of times it is perfectly fine to have a single component throw a single exception type with different messages for different errors. If the user cannot really do anything to handle the error specially, use the same generic exception class. If the user is able to handle them differently, that is when you should use a hierarchy.
  • For hierarchies, do not make all exceptions from different components inherit from a base exception. There is no real reason to do this. If the consumer wants to catch anything, they can simply catch Exception.
  • For package location, I put an Exception class with the code it relates to. So if I have a BusinessService in a package a.b.c, I have a a.b.c.BusinessException to go with it. I'm not a fan of putting all exceptions into an exceptions package. It just makes it hard to find.
查看更多
登录 后发表回答