Custom Exceptions
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
Exceptionclass to create your own checked exception. - Pass the error message to the parent constructor using
super(message). - Use
throw new MyException()to use it.
Enjoying these tutorials?