This chapter explains how to create and use custom (user-defined) exceptions in Java to handle application-specific errors.
A custom (user-defined) exception is an exception created by the programmer to handle application-specific error conditions. These exceptions are implemented by creating a class that extends either the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).
Custom exceptions allow developers to define meaningful error messages and handle errors in a way that better matches the program's requirements.
Here is the syntax to define a custom exception:
We can create a custom exception by extending the Exception class. In this example, we create a custom exception named WrongFileNameException.
Here, the string passed to the constructor is stored in the parent Exception class and can be retrieved using the getMessage() method.
Here is the complete example:
Output:
Caught Exception: Invalid file name: must end with .txt
Java exceptions cover almost all the general types of exceptions that may occur during code execution. However, we sometimes need to create custom exceptions.
The following are a few of the reasons to use custom exceptions:
To create a custom exception:
In this example, we create a custom exception InvalidAgeException that is thrown when the age is less than 18. The exception message is passed to the parent Exception class using super().
Output:
Caught the exception An exception occurred: InvalidAgeException: Age is not valid to vote Rest of the code...
In this example, we create a custom exception MyCustomException without a message. The exception is thrown and caught, demonstrating that getMessage() returns null if no message is provided.
Output:
Caught the exception null Rest of the code...
We request you to subscribe our newsletter for upcoming updates.