Monday, July 7, 2014

Things to remember while creating Custom Exception in Java

Things to remember while creating Custom Exception in Java

1) Don’t' use Exception to control application behaviour. Exception handling is very expensive as it require native calls to copy stacktrace, each time exception is created.

2) While creating custom exception, prefer to create an unchecked, Runtime exception than a checked exception, especially if you know that client is not going to take any reactive action other than logging.

3) If your custom exception is created by passing another exception, then always contain original Exception as source; use constructor which takes Exception rather than only message String.

4) Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as cause.

5) If possible avoid creating custom Exception and re-use existing, standard Exception classes from JDK itself. Most of the time you will realize that all you need is a form of IllegalArgumentException or ParseException or something similar.

6) While defining custom Exception, one of the most common mistake programmer make is to think that constructor is inherited from java.lang.Exception class, for example they think that their Exception class will automatically inherit default no argument constructor and the one which takes a String message. This is not true. Constructor is not inherited in Java, not even default constructor. It's actually added by compiler rather than inherited from parent class. That's why I have declared two constructor, one with String parameter and other as Throwable parameter :

public NoSuchProductException(String message, int productId) 
{ 
    super(message); 
    this.productId = productId; 
} 
public NoSuchProductException(String message, int productId, Throwable cause) 
{ 
    super(message, cause); 
    this.productId = productId; 
}

This is actually standard way of creating custom Exception in Java. In order to save time, you can even create template of above class in Eclipse IDE.

7) For readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class e.g. instead of naming your class IncorrectPassword, name it IncorrectPasswordException.

There is lot more given on the following link:
http://javarevisited.blogspot.in/2014/06/how-to-create-custom-exception-in-java.html

1 comment:

  1. Another good link you must study is

    http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/

    and decide, which one you would like to follow.

    ReplyDelete