BIG
DATA

JAVA

Custom Exceptions in Java

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Custom Exception class

The Java platform provides a lot of exception classes you can use. But if you choose to write one of your own, java alows you to do. Sometimes you need to create custom Exception in Java even though Joshua Bloch has recommended in Effective Java to prefer standard exception over custom exception.

According to oracle, You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

  • Do you need an exception type that isn't represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

To decide

Once you are sure to create a custom Exception class, you have few things to decide on. You have to decide whether your custom Exception will be a checked or unchecked exception. By default make your exception unchecked. General guideline is to make an exception unchecked if the client code is not going to take any action other than logging. If the exception will describe a coding mistake, you should subclass runtime exception. These exceptions could have been avoided in code and hence need not be handled. However if you are wrapping up a specific exception in a custom exception which should be handled up in the hierarchy, use Exception, or if possible a more specific Exception class.

Next is to choose a Superclass. Any Exception subclass can be used as the parent class of ypour custom exception. But dont choose a superclass which is either too specialized or completely unrelated to what you want.

Creating Exception Classes

Creating your own exception class in java is very simple. All you need to do is just extend "Exception" class or its subclasses for checked custom exception and extend RuntimeException or its subclasses for unchecked custom exception.

Creating custom checked exception

By extending java.lang.Exception, we can create checked exception.

class MyCustomException extends Exception {
 
    MyCustomException(String s) {
           super(s);
    }
 
}

Here "MyCustomException" is our exception class name and you can give any name of your choice. Note it extends "Exception" class. That is all you need to create a custom defined exception. Next you have a constructor which takes a "String" argument, where We call super class' constructor(super class here is "Exception" class) and pass this string to it. And then Java creates a new Exception with the message passed in the input String.

Similarly we can create an unchecked exception.

Creating custom unchecked exception

By extending java.lang.RuntimeException, we can create unchecked exception.

class MyCustomException extends RuntimeException {
 
    MyCustomException(String s) {
           super(s);
    }
 
}

Java Custom Exception Sample Code

class MyCustomException extends Exception {
 
    private String message = null;
 
    public MyCustomException() {
        super();
    }
 
    public MyCustomException(String message) {
        super(message);
        this.message = message;
    }
 
    public MyCustomException(Throwable cause) {
        super(cause);
    }
 
    @Override
    public String toString() {
        return message;
    }
 
    @Override
    public String getMessage() {
        return message;
    }
}
public class TestException {
    public static void main(String[] a){
        try{
            validate(null);
        } catch(MyCustomException ce){
            System.out.println("MyCustomException occured : "+ ce.getMessage());
        }
    }
     
    static void validate(String str) throws MyCustomException{
        if(str == null){
            throw new MyCustomException("value is null");
        }
    }
}

Output


MyCustomException occured : value is null

Points to note about Custom Exception

  • While creating a custom exception, prefer to create an unchecked exception over a checked exception. This will help programmers to be free of creating unnecessary try-catch blocks.
  • Exceptions are abnormal, undesired conditions, and as such should not be used for controlling the flow of execution of the programm. i.e. Don’t' use Exception to control application behavior because exception handling is very expensive as it requires native calls to copy stack trace, each time exception is created.
  • As a good practice, apart from providing default no argument constructor in your custom Exception class, consider providing at least two more constructors, one which should accept a string message and other which can accept another Throwable as the cause.
  • If your custom exception is created by passing another exception, then always contain original Exception as a source; use constructor which takes Exception rather than only message String.
  • Like Joshua Bloch has recommended in Effective Java, prefer standard exception over custom exception.If possible, avoid creating custom Exception and re-use existing, standard Exception classes from JDK itself.
  • It's good coding practice to append "Exception" to the names of all classes that inherits from the Exception class e.g. instead of naming your class InvalidAge, name it InvalidAgeException.