A user-defined custom exception is an exception class created by the programmer to represent application-specific or business-specific error scenarios.
Examples of User-defined Exception:
Invalid bank transaction
Insufficient balance
Age not eligible for registration
Invalid login attempt
Problem Without Custom Exceptions
Consider the following example:
Output
Error
Issues with This Approach:
The error message is unclear
No meaningful exception is thrown
Difficult to debug in large applications
Business logic and error handling are mixed
Solution: Using a User-Defined Custom Exception
Instead of printing vague messages, we can throw a meaningful custom exception.
This clearly explains the problem
Improves debugging
Separates business logic from error handling
throw new InvalidAgeException("Age must be 18 or above");
Custom Exception
A custom exception in Java is an exception defined by the user to handle specific application requirements. These exceptions extend either the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).
Why Use Java Custom Exceptions?
We use Java custom exception,
To represent application-specific errors.
To add clear, descriptive error messages for better debugging.
To encapsulate business logic errors in a meaningful way.
Checked Exceptions: It extends the Exception class. and it must be declared in the throws clause of the method signature.
Unchecked Exceptions: It extend RuntimeException and are not checked by the compiler, so they donβt need to be declared or handled. They usually represent programming errors or invalid operations.
How to Create a User-Defined Custom Exception
Create a class extending Exception or RuntimeException
Provide constructors with custom messages
(Optional) Add extra fields or methods
Example 1: Checked Custom Exception (Real-World Scenario)
Output
Caught Exception: Age must be 18 or above.
Explanation:
InvalidAgeException is a checked exception
The validate() method throws the exception if age is invalid
The exception must be handled in the main() method
This approach clearly separates validation logic and error handling
Example 2: Unchecked Custom Exception
Output
Caught Exception: Division by zero is not allowed.