0
0
Javaprogramming~5 mins

Creating custom exception class in Java

Choose your learning style9 modes available
Introduction

Sometimes, the built-in error messages are not clear enough. Creating a custom exception class helps you give clear, specific error messages for your program.

When you want to explain a special error in your program clearly.
When you want to separate different types of errors for better handling.
When you want to add extra information to an error.
When you want your program to react differently to different problems.
Syntax
Java
public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

You create a new class that extends Exception to make a checked exception.

The constructor passes the error message to the parent Exception class.

Examples
This creates a custom exception called AgeException with a message.
Java
public class AgeException extends Exception {
    public AgeException(String message) {
        super(message);
    }
}
This creates an unchecked exception by extending RuntimeException.
Java
public class MyRuntimeException extends RuntimeException {
    public MyRuntimeException(String message) {
        super(message);
    }
}
Sample Program

This program defines a custom exception AgeException. The checkAge method throws this exception if the age is less than 18. The main method calls checkAge with 16 and catches the exception to print the message.

Java
public class CustomExceptionDemo {
    static class AgeException extends Exception {
        public AgeException(String message) {
            super(message);
        }
    }

    public static void checkAge(int age) throws AgeException {
        if (age < 18) {
            throw new AgeException("Age must be at least 18");
        } else {
            System.out.println("Age is valid: " + age);
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (AgeException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}
OutputSuccess
Important Notes

Custom exceptions help make your program errors easier to understand.

Checked exceptions (extending Exception) must be declared or caught.

Unchecked exceptions (extending RuntimeException) do not require declaration.

Summary

Create a new class that extends Exception or RuntimeException.

Use a constructor to pass a message to the parent class.

Throw your custom exception where needed and catch it to handle errors clearly.