简体   繁体   中英

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?

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.

Well, simply put, if you do not need special exception class, you should not make one. If you do, then you make one. There's no magic to it really.

If you're making a library, then you should of course think from the point of view of the developers using the library (even if it is just you): does your library throw exceptions for specific reasons and could the library user possibly want to catch specifically these, because they can realistically do something about it (just logging isn't reason enough, IMO).

Example with standard exception classes: Caller of a method might want to convert IndexOutOfBoundsException to null return value, while letting other exceptions to propagate normally.

If you want your custom exception to be handled in default ways, you extend right existing exception class, such as IOException . You can then catch your specific IO exception when you want to do something specific just there, but also let it be handled like any other IOException when you don't need special handling (can't do anything useful to recover).

If you have a totally custom exception which should never be caught by a superclass catch, which always should have specific catch block, then you extend Exception directly.

I think it's pretty rare to need to extend RuntimeException , because if it an exception meant to be caught it should be Exception subclass, and if it's meant to end the program or just generate log output, then it should be covered by default RuntimeException implementations with custom message string.

  1. We will have a freedom to add few more methods into our Exception class which helps the client like rootCauseOfException(),description(),solution(),suggestions() etc. Can refer below link:
    https://stackoverflow.com/a/22698673

  2. If your project has interdependent modules then you can maintain exception hierarchy also in the same dependency hierarchy so that if you catch single Exception in base layer then all the interdependent modules exceptions will be caught.

  3. You can also mask some sensitive data like ip ,port etc before sending to client side. If custom exceptions are not used then some sensitive data can may get leaked to slient.

  4. You can provide your own exception message which can be easily understandable by client rather than java's exception message sometimes which may be hard to understand .

It is basically to Handle different Exception in different ways. Say, you might want to do some different operation on ArrayIndexOutOfBoundsException than a NumberFormatException.

or more clearly

}catch (ArrayIndexOutOfBoundsException ex){
//operation 1
}catch (NumberFormatException ex){
//operation 2
}

The main purpose would be identify the custom / app-specific errors. You can also provide some additional methods there. For eg, we have custom exceptions that return custom messages, and also extracts cause and location from the stack trace.

You need to have your client code know what exact exception happens by which part of code. so you need to let exception semantic and distinguished from other code block.

How to do this:

  1. Define new exception class, so the class name tells what happens
  2. Define a unifed/generic exception class which wraps code , message or other info. the code can tells what happens.

To summarize it, Do something let your exception have some meaning/semantics, and let its client know what exactly happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM