How and where do you define your own Exception hierarchy in Java?
My main question concerns package location where they your Exception classes must be defined.
Do we create a special package ourexceptions and put all classes inside it?
How and where do you define your own Exception hierarchy in Java?
My main question concerns package location where they your Exception classes must be defined.
Do we create a special package ourexceptions and put all classes inside it?
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.
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 use this as a general rule.
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.