Custom (User-Defined) Exception in Java

Last Updated : 14 Jan 2026

This chapter explains how to create and use custom (user-defined) exceptions in Java to handle application-specific errors.

What is Custom (User-Defined) Exception in Java?

A custom (user-defined) exception is an exception created by the programmer to handle application-specific error conditions. These exceptions are implemented by creating a class that extends either the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).

Custom exceptions allow developers to define meaningful error messages and handle errors in a way that better matches the program's requirements.

Syntax

Here is the syntax to define a custom exception:

Custom Exception Example: WrongFileNameException

We can create a custom exception by extending the Exception class. In this example, we create a custom exception named WrongFileNameException.

Here, the string passed to the constructor is stored in the parent Exception class and can be retrieved using the getMessage() method.

Complete Example Using WrongFileNameException

Here is the complete example:

Output:

Caught Exception: Invalid file name: must end with .txt

Why use custom exceptions?

Java exceptions cover almost all the general types of exceptions that may occur during code execution. However, we sometimes need to create custom exceptions.

The following are a few of the reasons to use custom exceptions:

  • It represents application-specific errors.
  • To catch and provide specific treatment to a subset of existing Java exceptions.
  • Business Logic Exceptions: These are the exceptions related to business logic and workflow. It is useful for users and developers to understand the exact problem in a meaningful way.
  • It provides clear, descriptive error messages for better debugging.

Creating a Custom Exception

To create a custom exception:

  1. You need to extend the Exception class (for checked exceptions) or RuntimeException class (for unchecked exceptions).
  2. After that, you need to initialize the exception with custom messages using the constructor.
  3. Optionally, you can also add methods to provide additional details about the exception.

Example 1: Custom Exception with Message

In this example, we create a custom exception InvalidAgeException that is thrown when the age is less than 18. The exception message is passed to the parent Exception class using super().

Compile and Run

Output:

Caught the exception
An exception occurred: InvalidAgeException: Age is not valid to vote
Rest of the code...

Example 2: Custom Exception Without Message

In this example, we create a custom exception MyCustomException without a message. The exception is thrown and caught, demonstrating that getMessage() returns null if no message is provided.

Compile and Run

Output:

Caught the exception
null
Rest of the code...