Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
rajesh Avatar asked Mar 19 '13 06:03

rajesh


People also ask

Why would I use a custom exception class?

The purpose of a custom exception class is to integrate the look-up of localized message strings in a custom message catalog into the mechanism that is used for error reporting in the client infrastructure.

Should I use custom exceptions?

Having custom exceptions - tailored to your specific use cases and that you can raise and catch in specific circumstances - can make your code much more readable and robust, and reduce the amount of code you write later to try and figure out what exactly went wrong.

What is the purpose of exceptions in Java?

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code.


3 Answers

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.
like image 123
NPE Avatar answered Nov 02 '22 23:11

NPE


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.

like image 39
hyde Avatar answered Nov 02 '22 22:11

hyde


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.

like image 37
Henry Leu Avatar answered Nov 03 '22 00:11

Henry Leu