Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

oop - Why should we write custom exception classes in Java

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...