Train Smart. Work Smarter.
May 30, 2023 admin
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.