Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 473
EugeneP Avatar asked Apr 21 '10 13:04

EugeneP


People also ask

What is the hierarchy of exceptions in Java?

The hierarchy of Exceptions in the Java programming language begins with the Throwable class – which comes from the Object class and is its direct subclasswhileThe Exception class presents all This Throwable class further branches into two subclasses – Error and Exception.

How can you create your own exception in Java?

In order to create a custom exception, we need to extend the Exception class that belongs to java. lang package. Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.

How would you make your own checked exception?

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.


1 Answers

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.
like image 81
Chris Dail Avatar answered Oct 14 '22 03:10

Chris Dail