How To Create Custom Exception in Java

In this article, we learn the custom exception in java or user-defined exception in java, why to use custom exceptions, and examples of custom exceptions.

Custom Exception in Java

In Java, you can create your own exceptions that are derived from the Exception class. Creating your own exceptions is known as a custom exception in java or a user-defined exception in java. Essentially, the custom exception in java is used to customize exceptions according to user needs.

Custom exceptions allow you to create your own exceptions and messages. Here we passed a string to the constructor of the superclass, the Exception class, which can be retrieved using the getMessage() method on the created object.

Why use custom exception in Java?

Java Exceptions covers almost all of the common types of exceptions that can occur in programming. However, there may be times when you need to create custom exceptions.

Here are some reasons to use custom exceptions:

  • Catch a subset of the existing Java exceptions and provide specific handling.
  • Business Logic Exceptions: Exceptions related to business logic and workflow. It helps the application user or developer to understand the exact problem.

To create a custom exception you need to extend the Exception class which belongs to java.lang package.

Consider the following example that creates a custom exception named WrongFileNameException.

public class WrongFileNameException extends Exception { 

    public WrongFileNameException(String errorMessage) { 

    super(errorMessage); 

    } 

}

Custom Exception in Java Example

Let’s look at a simple example of Java custom exceptions. In the following code, the constructor for InvalidAgeException takes a string as an argument. This string is passed to the constructor of the parent class Exception using the super() method. Also, the exception class constructor can be called without parameters, and calling the super() method is not required.

Custom Exception in Java Example

Output:

Caught the exception

Exception occurred: InvalidAgeException: age is not valid to vote

Rest of the code…

Other Popular Articles

Number Format Exception In Java

Leave a Comment