Open In App

User-Defined Custom Exception in Java

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, an Exception is an issue (run-time error) that occurs during the execution of a program. When an exception occurs, the program terminates abruptly, and the code beyond the exception never gets executed.

Java provides us the facility to create our own exceptions by extending the 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.

Java
// A Class that represents user-defined exception
class MyException extends Exception {
    public MyException(String m) {
        super(m);
    }
}

// A Class that uses the above MyException
public class setText {
    public static void main(String args[]) {
        try {
            
            // Throw an object of user-defined exception
            throw new MyException("This is a custom exception");  
        }
        catch (MyException ex) {
            System.out.println("Caught");  
            System.out.println(ex.getMessage());  
        }
    }
}

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)

Java
// Custom Checked Exception
class InvalidAgeException extends Exception {
    public InvalidAgeException(String m) {
        super(m);  
    }
}

// Using the Custom Exception
public class Geeks {
    public static void validate(int age) 
      throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above.");
        }
        System.out.println("Valid age: " + age);
    }

    public static void main(String[] args) {
        try {
            validate(12);
        } catch (InvalidAgeException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

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

Java
// Custom Unchecked Exception
class DivideByZeroException extends RuntimeException {
    public DivideByZeroException(String m) {
        super(m);
    } 
}

// Using the Custom Exception
public class Geeks {
    public static void divide(int a, int b) {
        if (b == 0) {
            throw new DivideByZeroException("Division by zero is not allowed.");
        }
        System.out.println("Result: " + (a / b));
    }

    public static void main(String[] args) {
        try {
            divide(10, 0);
        } catch (DivideByZeroException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
    }
}

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.



Next Article
Article Tags :
Practice Tags :

Similar Reads