Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the general rule of thumbs for creating an Exception in Java?

Tags:

I have been in both situations:

  • Creating too many custom Exceptions
  • Using too many general Exception class

In both cases the project started OK but soon became an overhead to maintain (and refactor).

So what is the best practice regarding the creation of your own Exception classes?

like image 839
pek Avatar asked Aug 25 '08 21:08

pek


People also ask

How do you create an exception in Java?

To create a custom exception, we have to extend the java. lang. Exception class. Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.

What are the 3 specific keywords used in exception handling?

The exception handling fundamentals in Java revolve around the five keywords- try, catch, finally, throw, and throws. These keywords form the base of exception handling. All the exception handling mechanisms in Java are a result of these five keywords.


1 Answers

The Java Specialists wrote a post about Exceptions in Java, and in it they list a few "best practices" for creating Exceptions, summarized below:

  • Don't Write Own Exceptions (there are lots of useful Exceptions that are already part of the Java API)

  • Write Useful Exceptions (if you have to write your own Exceptions, make sure they provide useful information about the problem that occurred)

like image 138
Josh Brown Avatar answered Sep 17 '22 16:09

Josh Brown