Techoceanhub logo

Throwing and catching custom exceptions

In Java, you can throw and catch custom exceptions to handle specific errors or exceptional situations in your code. To create a custom exception, you need to extend the Exception class or one of its subclasses. Here’s an example of how you can throw and catch a custom exception:

// Custom exception class
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

// Example method that throws a custom exception
public void doSomething() throws CustomException {
    // Perform some operation
    // If an exceptional situation occurs, throw the custom exception
    throw new CustomException("An error occurred!");
}

// Example usage of the doSomething method
public static void main(String[] args) {
    try {
        // Call the method that throws the custom exception
        doSomething();
    } catch (CustomException e) {
        // Catch the custom exception and handle it
        System.out.println("Caught custom exception: " + e.getMessage());
    }
}

In the example above, the CustomException class extends the Exception class. It has a constructor that accepts a message parameter, which is used to provide additional details about the exception. The doSomething() method throws the custom exception by creating a new instance of CustomException and throwing it.

In the main method, we call doSomething() inside a try-catch block. If the doSomething() method throws a CustomException, it is caught in the catch block, and the corresponding message is printed.

You can define and use multiple custom exceptions by creating additional classes that extend Exception or its subclasses.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .