Custom Exception Class

In Java, a custom exception is a user-defined class that extends the Exception class or one of its subclasses, such as RuntimeException. Custom exceptions help in providing more meaningful error messages specific to our application.

Basic Custom Exception

To create a custom exception, we just need to create a class that extends the Exception class.

Throwing the Custom Exception

To throw the custom exception, use the throw keyword within a method.

Custom Exception with Multiple Constructors

We can add multiple constructors to our custom exception class. For example, one with a message and one with both a message and a cause.

Runtime Custom Exception

If we want our exception to be unchecked (doesn’t require a try-catch block or throws declaration), we can extend RuntimeException instead of Exception.