What is a Custom Exception?
A custom exception is a user-defined exception class in Java that extends the Exception
or RuntimeException
class. It allows developers to create meaningful and specific exceptions that provide more context about the errors occurring in an application.
Why Use Custom Exceptions?
- Specific Error Handling:
- Custom exceptions help provide more clarity and detail about an error, allowing for more accurate and specific error handling.
- Example: Instead of throwing a generic
Exception
for invalid input, aInvalidUserInputException
might make the problem more explicit. - Enhanced Readability and Maintenance:
- Custom exceptions make code easier to read and maintain because they convey the exact cause of an error.
- Example: A
FileFormatException
can be created to handle errors related to file parsing. - Custom Messages:
- They allow the inclusion of custom error messages, which can provide detailed information about what went wrong.
- Example:
"User ID cannot be negative"
can be passed as a message in aNegativeUserIdException
.
❓ How to Create a Custom Exception?
- Extend Exception or RuntimeException:
- Extend the
Exception
class if you want to create a checked exception (needs to be declared in the method signature withthrows
). - Extend the
RuntimeException
class for unchecked exceptions (doesn't require declaring in the method signature).
Example:
java
public class InvalidUserInputException extends Exception {
public InvalidUserInputException(String message) {
super(message);
}
}
- Throwing the Custom Exception:
- You can throw the custom exception where the error condition occurs in the code.
Example:
java
public void validateUserId(int userId) throws InvalidUserInputException {
if (userId < 0) {
throw new InvalidUserInputException("User ID cannot be negative");
}
}
- Catching the Custom Exception:
- You can catch and handle custom exceptions just like any other exception using a
try-catch
block.
Example:
java
try {
validateUserId(-1);
} catch (InvalidUserInputException e) {
System.out.println(e.getMessage());
}