Skip to content

Custom Exceptions in Java

Think of them as personalized error messages tailor-made to suit your application's needs. While Java comes with a set of built-in exceptions to handle common errors, custom exceptions allow you to define your own types of errors, complete with specific error messages and behaviors.To create a custom exception we need to create a class that extends Exception class

Example

java
// Define a custom exception class
class NegativeNumberException extends Exception {
    NegativeNumberException() {
        super("Number cannot be negative!");
    }
}

// Create a method that throws our custom exception
class Calculator {
    static int divide(int dividend, int divisor) throws NegativeNumberException {
        if (divisor < 0) {
            throw new NegativeNumberException();
        }
        return dividend / divisor;
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int result = Calculator.divide(10, -2);
            System.out.println("Result: " + result);
        } catch (NegativeNumberException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

In this example, we've defined a custom exception class called NegativeNumberException, which extends Java's built-in Exception class. We've provided a constructor that sets the error message to "Number cannot be negative!"

Next, we have a Calculator class with a divide() method. If the divisor is negative, we throw our custom NegativeNumberException. In the main() method, we catch this exception and handle it gracefully by printing the error message.

With custom exceptions, we can tailor our error handling to specific scenarios, providing clear and meaningful feedback to users when something goes wrong.

But wait, there's more! Custom exceptions can also have additional fields and methods, allowing you to pass extra information or perform custom error handling logic.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.