Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Custom Java Exception

An exception is an undesirable event that occurs when executing a program. Exceptions disturb the normal flow of execution of our code. Java defines a lot of in-built exceptions that cover different scenarios in which an error can occur. However, we may need custom exceptions to deal with some special cases. In this tutorial, we will learn how to create custom exceptions in Java.

Why do we Need Custom Exceptions?

  • Java provides different exceptions, and they cover almost every case that we may encounter during programming. But there are a few cases where we may need a custom exception.
  • For example, consider that we have a Bank class. If the account balance goes below $0, then we may need to throw an InsufficientFundsException.
  • The following are the two general scenarios where we may need custom, user-defined exceptions.
    • Exceptions that are related to our business logic or workflow(like the Bank example).
    • To provide specific processing for existing exceptions.

Custom Checked Exceptions

Checked exceptions are exceptions that are checked during compile time. If some part of the code throws a checked exception, it must be handled using try-catch blocks or the throws keyword in the method definition.

To create a user-defined checked exception, we need to extend the Exception class.

Example

Let's create a MyArray class and implement a get() method. This method will throw an IndexNotValidException exception if the index is invalid.

//Custom Checked exception
class IndexNotValidException extends Exception
{
	IndexNotValidException(String msg)//Constructor with error message
	{
		super(msg);
	}
}	
class MyArray
{
	int[] array;
	MyArray(int size)//Constructor for our array class
	{
		array = new int[size];
		for(int i=0; i<size; i++)
			array[i] = i*5;
	}	
	//Get Method may throw IndexNotValidException
	public int get(int index) throws IndexNotValidException
	{
		if(index >= array.length)
			throw new IndexNotValidException("Index " + index+ " is invalid.");//Throwing the exception
			
		else
			return array[index];
	}
}
public class Demo
{	
	public static void main(String[] args)
	{
			MyArray arr = new MyArray(5);
			try {
				arr.get(10);//Error
			} 
			catch (IndexNotValidException e) {
				e.printStackTrace();
			}
	}
}


IndexNotValidException: Index 10 is invalid.
at MyArray.get(Demo.java:24)
at Demo.main(Demo.java:39)

As shown in the code above, the IndexNotValidException extends the Exception class. We have used a constructor in the IndexNotValidException class. This calls the parent constructor with the error message.

Custom Unchecked Exceptions

Unchecked exceptions are not checked during the compile time. Such exceptions are only detected during runtime. To create a custom unchecked exception, we need to extend the RuntimeException class.

Example

We can extend the RuntimeException class instead of the Exception class to create an unchecked exception. We can also define a Throwable exception that defines the underlying exception or the cause of our exception. The underlying exception in our case is ArrayIndexOutOfBounds. The complete code for this is shown below.

//Custom Unchecked exception
class IndexNotValidException extends RuntimeException
{
	IndexNotValidException(String msg, Throwable cause)//Constructor with error message and cause 
	{
		super(msg, cause);
	}
}	
class MyArray
{
	int[] array;
	MyArray(int size)//Constructor for our array class
	{
		array = new int[size];
		for(int i=0; i<size; i++)
			array[i] = i*5;
	}	
	//Get Method may throw IndexNotValidException
	public int get(int index) throws IndexNotValidException
	{
		if(index >= array.length)
		{
			Exception cause = new ArrayIndexOutOfBoundsException();//Cause of our exception
			throw new IndexNotValidException("Index " + index+ " is invalid.", cause);//Throwing the exception
		}			
		else
			return array[index];
	}
}
public class Demo
{
	
	public static void main(String[] args)
	{
			MyArray arr = new MyArray(5);
			arr.get(10);//Exception occurs here
	}
}


Exception in thread "main" IndexNotValidException: Index 10 is invalid.
at MyArray.get(Demo.java:24)
at Demo.main(Demo.java:39)
Caused by: java.lang.ArrayIndexOutOfBoundsException
at MyArray.get(Demo.java:23)
... 1 more

Summary

Exceptions and errors are very common when we work with any programming language. Custom exceptions help us in identifying errors that are specific to our own application. Custom exceptions are used to identify errors in our business logic and workflow. They are also used to build something on top of the existing exceptions.