How to create a custom exception in Java

Learn how to create a custom exception in Java. In this post, we will see how user defined exceptions are implemented and used for checked and unchecked exceptions. Also, we will call JDK exceptions as built-in exceptions whereas calling our exceptions custom exceptions or user defined exceptions.

Read Also: Exception Handling Interview Questions and Answers

Why do we need Custom Exception?

No doubt! Java programming provides all general exceptions that are bound to happen in programming. Suppose you are writing your own Java project, namely, Simple Banking Management application. You want to throw InvalidAccountNumberException, NameMismatchException, or similarly any other exception. How do you throw such exceptions? Such exceptions are not provided by the JDK also.
In a one-liner, for business logic exceptions. This helps the developers or users to understand what exactly the problem is.

Creating Your Own Custom Exception Class

Let's create the custom exception. Below are the steps you need to follow to create a custom exception in Java.
1. Create a new class with a name ending with Exception like ArithmeticException.
2. extends newly created class with subtypes of the java.lang.Exception class. Usually, a user defined exception class always extends directly from the Exception class.
3. This is the most important part of creating the user defined exception in Java. Create a constructor in the newly created class that takes a single String parameter that contains the detailed message of the exception. In this constructor, just call the super constructor and pass the message as shown below:

Example

class InvalidAccountNumberException extends Exception {
    public InvalidAccountNumberException(String message) {
        super(message);
    }
}


Let's use the above custom exception in the Java code example:

class BankAccountManager {
    public BankAccount find(String accountNumber) throws InvalidAccountNumberException{
        if(accountNumber.equals("123456789")) {
            return new BankAccount();
        }
        else {
            throw new InvalidAccountNumberException(" Bank AccountNumber is not found :- "
                                                        + accountNumber);
        }
    }
}


The above example shows that custom exception is used in a similar manner as Java built-in exceptions. Below is the test program to handle the exception:

class BankAccount{
    public String accountNumber;
}
public class BankAccountTest {
    public static void main(String args[]) {
    BankAccountManager obj = new BankAccountManager();
    try {
        BankAccount bankAccount = obj.find("08041989");
    }
    catch(InvalidAccountNumberException ex) {
        System.out.println(ex);
    }
  }
}


Output:
InvalidAccountNumberException: Bank AccountNumber is not found :- 08041989

Add Throwable Example

We have created the custom exception but if you analyze the above code, you will find that you are losing the root cause of the exception. To solve this issue, we can also add a java.lang.Throwable parameter to the constructor. This way we can also get the root cause of the exception.

class InvalidAccountNumberException extends Exception {
    public InvalidAccountNumberException(String message, Throwable err) {
        super(message, err);
    }
    public InvalidAccountNumberException(String message) {
        super(message);
    }
}


Modify the BankAccountTest.java file as shown below:

public class BankAccountTest {
    public static void main(String args[]) throws InvalidAccountNumberException{
    BankAccountManager obj = new BankAccountManager();
    try {
        BankAccount bankAccount = obj.find("08041989");
    }
    catch(InvalidAccountNumberException ex) {
        throw new InvalidAccountNumberException(" Bank AccountNumber is not found :- "
                                                        , ex);
    }
  }
}



Output:
Exception in thread "main" InvalidAccountNumberException: Bank AccountNumber is not found :-
at BankAccountTest.main(BankAccountTest.java:8)
Caused by: InvalidAccountNumberException: Bank AccountNumber is not found :- 08041989
at BankAccountManager.find(BankAccountTest.java:22)
at BankAccountTest.main(BankAccountTest.java:5)

Custom Unchecked Exception Example

To create the custom unchecked exception, all we need to do is just extends the java.lang.RuntimeException class as shown below in the example.

class InvalidAccountNumberException extends RuntimeException {
    public InvalidAccountNumberException(String message, Throwable err) {
        super(message, err);
    }
}


That's all for today. Please mention in the comments in case you have any questions related to how to create a custom exception in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry