Web Analytics

Custom Exceptions

Intermediate ~15 min read

You can create your own exceptions (User-Defined Exceptions) to handle specific errors in your application logic that standard Java exceptions don't cover.

How to Create

To create a custom exception, just create a class that extends Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).

class InvalidAgeException extends Exception {
    public InvalidAgeException(String errorMessage) {
        super(errorMessage);
    }
}

Using Custom Exceptions

Once defined, you use the throw keyword to throw it.

throw new InvalidAgeException("Age is too low!");

Full Example

Output
Click Run to execute your code

Summary

  • Extend Exception class to create your own checked exception.
  • Pass the error message to the parent constructor using super(message).
  • Use throw new MyException() to use it.