Custom Exceptions
A custom exception is an exception class you create yourself, usually to represent a very specific problem related to your own application's logic, which Java's built-in exceptions don't already describe well.
1. What is a Custom Exception?
A custom exception is an exception class you create yourself, usually to represent a very specific problem related to your own application's logic, which Java's built-in exceptions don't already describe well.
2. Why is it used?
Built-in exceptions are quite general. Creating your own, clearly named exception (like InsufficientBalanceException) makes your error handling more meaningful and easier for other developers to understand.
3. Real-Life Example
Think of a company creating its own specific complaint category, like "Late Delivery Complaint," instead of just using a generic "Issue" label for every problem. A custom exception gives a specific, meaningful name to a specific kind of problem.
4. Syntax
javaclass CustomExceptionName extends Exception { CustomExceptionName(String message) { super(message); } }
5. Example Program
javaclass InsufficientBalanceException extends Exception { InsufficientBalanceException(String message) { super(message); } } public class CustomExceptionDemo { static void withdraw(double balance, double amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("Not enough balance!"); } System.out.println("Withdrawal successful."); } public static void main(String[] args) { try { withdraw(1000, 5000); } catch (InsufficientBalanceException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Error: Not enough balance!6. Key Points to Remember
- A custom exception usually extends
Exception(checked) orRuntimeException(unchecked), depending on the intended use. - Using
super(message)passes the error message up to the built-in exception behaviour. - Custom exceptions make error messages in large applications much clearer and more specific.