Custom (User-Defined) Exception in JavaLast Updated : 14 Jan 2026 This chapter explains how to create and use custom (user-defined) exceptions in Java to handle application-specific errors. What is Custom (User-Defined) Exception in Java?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. SyntaxHere is the syntax to define a custom exception: Custom Exception Example: WrongFileNameExceptionWe 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. Complete Example Using WrongFileNameExceptionHere is the complete example: Output: Caught Exception: Invalid file name: must end with .txt Why use custom exceptions?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:
Creating a Custom ExceptionTo create a custom exception:
Example 1: Custom Exception with MessageIn 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... Example 2: Custom Exception Without MessageIn 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... Next TopicJava Inner class |
We request you to subscribe our newsletter for upcoming updates.