Custom Exception

Custom exceptions are also called as user defined exceptions

We know that, Java has already provided bunch of exceptions to handle various scenarios like ArithmeticException,NullPointerException,ArrayIndexOutOfBoundException etc.

These exceptions will be thrown by java based on pre-defined conditions

ArithmeticException will be thrown whenever we divide number by zero

NullPointerException will be thrown whenever we access method or variable using NULL reference

ArrayIndexOutOfBoundException will be thrown whenever we access element from array using index out of its limit

We have seen how to throw these exceptions in our previous articles.

Let’s see how to create our own custom exception


We can create custom exception in java by extending Exception or RunTimeException

Example :

MyCustomException.java

  1. class MyCustomException extends Exception {
  2. String message;
  3.  
  4. MyCustomException(String message) {
  5.     this.message=message;
  6.    }
  7.    
  8.    public String toString(){
  9.     return ("MyCustomException: "+message) ;
  10.    }
  11.  }
class MyCustomException extends Exception {
String message;

MyCustomException(String message) {
	this.message=message;
   }
   
   public String toString(){ 
	return ("MyCustomException: "+message) ;
   }
 }


CustomExceptionExample.java

  1. public class CustomExceptionExample{
  2.    public static void main(String args[]){
  3.    int age=30;
  4.     try{
  5.         System.out.println("Begin: try block");
  6.         // Throwing custom exception based on condition using throw
  7.        
  8.         if(age > 25){
  9.         throw new MyCustomException("Age can not be greater than 25");
  10.         }
  11.     }
  12.     catch(MyCustomException e){
  13.         System.out.println("Custom exception handler : Catch Block");
  14.         System.out.println(e) ;
  15.     }
  16.    }
  17. }
public class CustomExceptionExample{
   public static void main(String args[]){
   int age=30;
	try{
		System.out.println("Begin: try block");
		// Throwing custom exception based on condition using throw
		
		if(age > 25){
		throw new MyCustomException("Age can not be greater than 25");
		}
	}
	catch(MyCustomException e){
		System.out.println("Custom exception handler : Catch Block");
		System.out.println(e) ;
	}
   }
}


In the above example, we have created custom exception by extending Exception class

We have created one parameterized constructor to throw custom exception with message

We have thrown custom exception using throw keyword based on business condition(age >25)

We can also create custom exception by extending RunTimeException class

Example :

InvalidCustomerException.java

  1. class InvalidCustomerException extends RunTimeException
  2. {
  3.     public InvalidCustomerException(String s)
  4.     {
  5.         // Call constructor of parent RunTimeException
  6.         super(s);
  7.     }
  8. }
class InvalidCustomerException extends RunTimeException
{
    public InvalidCustomerException(String s)
    {
        // Call constructor of parent RunTimeException
        super(s);
    }
}


CustomExceptionExample.java

  1. public class CustomExceptionExample
  2. {
  3.    void validateCustomer(int customerId) throws InvalidCustomerException {
  4.     if(customerId>10000){
  5.         throw new InvalidCustomerException("Invalid Customer");
  6.     }
  7.    }
  8.    
  9.     public static void main(String args[])
  10.     {
  11.         CustomExceptionExample obj = new CustomExceptionExample();
  12.         try
  13.         {
  14.             obj.validateCustomer(20000);
  15.         }
  16.         catch (InvalidCustomerException e)
  17.         {
  18.             System.out.println("Catching exception");
  19.             System.out.println(e.getMessage());
  20.         }
  21.     }
  22. }
public class CustomExceptionExample
{
   void validateCustomer(int customerId) throws InvalidCustomerException {
	if(customerId>10000){
		throw new InvalidCustomerException("Invalid Customer");
	}
   }
   
    public static void main(String args[])
    {
    	CustomExceptionExample obj = new CustomExceptionExample();
        try
        {
            obj.validateCustomer(20000);
        }
        catch (InvalidCustomerException e)
        {
            System.out.println("Catching exception");
            System.out.println(e.getMessage());
        }
    }
}


In the above example, we have created custom exception by extending RunTimeException

We have thrown RunTimeException in the method based on business condition(customerId >10000)

Note :
Using throws keyword in the method declaration is optional for RunTimeException


When to use custom exception?


We should not simply create custom exceptions unless and until there is a need

We should create custom exceptions only when we need to send some useful information to client

Example, Jackson defines JsonProcessingException which inherits IOException.

If we catch it, we can obtain location information of the parse error using getLocation()

Consider below Example

  1. public class InvalidNumberException extends Exception
  2. {
  3. }
public class InvalidNumberException extends Exception 
{
}


This exception is not giving any useful information to the client code, other than custom exception name

We know that Exception classes are like any other java class where we can add methods that we think client invokes such methods to get more information

Example

  1. public class InvalidNumberException extends Exception
  2. {
  3. private int number;
  4. public InvalidNumberException (int number){
  5.         this.number=number;
  6.         }
  7.     public int getNumber(){
  8.     return number;
  9.     }
  10.    
  11. }
public class InvalidNumberException extends Exception 
{
private int number;
public InvalidNumberException (int number){
		this.number=number;
		}
    public int getNumber(){
	return number;
	}
   
}


In the above example, client can use getNumber() method to get the number which is invalid

Note :
If we need to pass additional information to client then custom exceptions are the best choice

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on