Why should we write custom exception classes in Java

exception, java, oop

Solution

I can think of several reasons:

- Having multiple exception classes allows the programmer to be specific in their `catch` clauses, and only catch the exceptions they care about and know what to do with.

- An exception class can carry information about the error that's caused the exception. For example, `ArrayIndexOutOfBoundsException` carries the offending array index, and SQL exceptions tends to carry database-specific error codes and messages.

- Exception specifications -- that list exception classes -- can be used to check correctness at compile time.

Problem

What is the purpose of writing custom exception classes when mostly what it does is same. For eg, NullPointerException: ``` class NullPointerException extends RuntimeException { private static final long serialVersionUID = 5162710183389028792L; public NullPointerException() { super(); } public NullPointerException(String s) { super(s); } } ``` This is the basic template for most exception classes that I have seen and created. One purpose I can think of is in handling these exception.But then cant this be based on Exception Message?. Mostly we write single handling code for each exception type. I know there are 'exceptions' to this. But is there anything more to it? Isnt this repeating yourself where only the class name changes? Also are there any JDK Exception classes that has some code than this?

Original source

Related problems