Java Custom Exception – User Defined Exceptions

Filed Under: Java

Custom Exceptions or User-Defined Exceptions are very common in Java applications. We can easily create custom exception classes for different use cases.


What are the different types of Exceptions?

In Java, there are two categories of Exceptions:

  • Checked Exceptions – These are recoverable. These are derived from the Exception class. For example, IOException and FileNotFoundException are checked exceptions.
  • Unchecked Exceptions – These are not recoverable and occur at runtime. These are derived from java.lang.RuntimeException class. For example, NullPointerException and IllegalArgumentException are unchecked exceptions.

Further Reading: Exception Handling in Java.

Moving ahead, let’s look at custom exceptions in the next section.


Java Custom Exceptions or User-Defined Exceptions

Custom Exceptions are user-defined exceptions. These are written by programmers specifically for there application use cases.

To create a checked custom exception, it must extend Exception or its child classes.

Unchecked custom exception extends RuntimeException or its child classes.

All Exceptions are a child of Throwable.

Before we get down to the implementation part, let’s make note of a few points.

  • Create Custom Exceptions only when they provide a specific use case that none of the available Exceptions provide.
  • All custom exceptions must follow the standard naming convention. That is camel case and ending with the word “Exception”.
  • Use overloaded constructors for all scenarios.

1. Custom Unchecked Exceptions

An example of custom unchecked exceptions is given below.


package com.journaldev.java;

import java.util.ArrayList;

public class CustomExceptions {


    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();

        arrayList.add("Monday");
        arrayList.add("Tuesday");
        arrayList.add("Wednesday");

        String day = "Sunday";

        if (!arrayList.contains(day)) {

            try {
                throw new DayNotAvailableException("Day not available",day);
            } catch (DayNotAvailableException e) {
                e.getLocalizedMessage();
                e.printStackTrace();
            }
        }

    }
}


class DayNotAvailableException extends RuntimeException {

    private String day;

    public DayNotAvailableException() {
        super();
    }

    public DayNotAvailableException(String message, String day) {
        super(message);
        this.day = day;
    }

    public DayNotAvailableException(String message, String day, Throwable cause) {
        super(message, cause);
        this.day = day;
    }

    @Override
    public String toString() {
        return super.toString();
    }

    @Override
    public String getMessage() {
        return super.getMessage() + " for the day :" + day;
    }

    @Override
    public String getLocalizedMessage() {
        return "The day "+day + " is not available.";
    }
}
Java Custom Checked Exceptions

Java Custom Unchecked Exception

In the above program, we simply throw an error when the value is not present in the ArrayList.

In the custom exception, we have defined multiple constructors to cover different cases.

The getMessage() and getLocalisedMessage() are overridden to provide custom responses.


2. User-Defined Checked Exception

Here is a simple example of user-defined checked exception. We will extend the Exception class and override the toString() method.


package com.journaldev.java;

public class EmployeeNotFoundException extends Exception {

	private static final long serialVersionUID = -2872694086602732648L;

	private int id;

	EmployeeNotFoundException(int i, String message) {
		super(message);
		this.id = i;
	}

	EmployeeNotFoundException(int i, String message, String cause) {
		super(message, new Throwable(cause));
		this.id = i;
	}

	@Override
	public String toString() {
		return String.format("EmployeeNotFoundException[%d]", this.id);
	}

}

Conclusion

Summing up, Custom Exceptions behave like built-in Exception types. Create a custom exception whenever you need to handle your application/module specific exceptions and boundaries.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages