(Translated by https://www.hiragana.jp/)
User-Defined Custom Exception in Java - GeeksforGeeks
Open In App

User-Defined Custom Exception in Java

Last Updated : 14 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Java provides us the facility to create our own exceptions by extending the Java Exception class. Creating our own Exception is known as a custom exception in Java or a user-defined exception in Java. In simple words, we can say that a User-Defined Custom Exception or custom exception is creating your own exception class and throwing that exception using the "throw" keyword.

Now, before understanding the concept in depth, let's go through the example below:

Example: In this example, a custom exception MyException is created and thrown in the program.


Output
Caught
This is a custom exception

Java Custom Exception

A custom exception in Java is an exception defined by the user to handle specific application requirements. These exceptions extend either the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).

Why Use Java Custom Exceptions?

We use Java custom exception,

  • To represent application-specific errors.
  • To add clear, descriptive error messages for better debugging.
  • To encapsulate business logic errors in a meaningful way.

Types of Custom Exceptions

There are two types of custom exceptions in Java.

Create a User-Defined Custom Exception

  1. Create a new class that extends Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).
  2. Provide constructors to initialize the exception with custom messages.
  3. Add methods to provide additional details about the exception. (this is optional)

Example 1: Checked Custom Exception (Real-World Scenario)


Output
Caught Exception: Age must be 18 or above.

Explanation: The above example defines a custom checked exception InvalidAgeException that is thrown when an age is below 18. The validate() method checks the age and throws the exception if the age is invalid. In the main() method, the exception is caught and the error message is printed.


Example 2: Unchecked Custom Exception


Output
Caught Exception: Division by zero is not allowed.

Explanation: The above example defines a custom unchecked exception DivideByZeroException that is thrown when we are trying to divide by zero. The divide() method checks if the denominator is zero and throws the exception if true. In the main() method, the exception is caught and the error message is printed.


User Defined Exceptions
Visit Course explore course icon
Video Thumbnail

User Defined Exceptions

Video Thumbnail

User-defined Custom Exception in Java

Article Tags :
Practice Tags :

Similar Reads