Java Custom Exception Handling Guide

In Java, capturing a custom exception is similar to capturing a system-defined exception. Firstly, you need to define a custom exception class, typically inheriting from the Exception class or its subclass.

For example, let’s say we have a custom exception class called MyException:

public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
}

Then, throw a custom exception in the program and catch it.

public class Main {
    public static void main(String[] args) {
        try {
            throw new MyException("This is a custom exception");
        } catch (MyException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }
}

In the example above, we threw a custom exception, MyException, in the try block and caught and handled it in the catch block. When the custom exception is caught, the code in the catch block is executed and the exception message is printed.

bannerAds