Java Essentials: Handling Errors with Exceptions
What Is an Exception?
An exception is an event that interrupts the normal flow of a program. Java models failures as objects. When code runs into a problem, it throws an exception, and the runtime looks for a handler. Without a handler, the program prints a stack trace and stops.
Try, Catch, and Finally
The try block holds code that might fail. The catch block handles a specific exception type. The finally block runs whether an exception happened or not, which makes it perfect for closing files or releasing resources.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Cleanup always runs");
}The program does not crash: it prints a friendly message and then runs the finally block. You can catch several exception types with separate catch blocks, and the most specific type must be listed first.
Checked and Unchecked Exceptions
Checked exceptions, like IOException, must be declared or caught or the code will not compile. Unchecked exceptions, like NullPointerException, do not force you to handle them. Libraries and frameworks throw both kinds, so reading the method signature tells you which ones to expect.
Throwing and Creating Exceptions
You can raise your own errors with the throw keyword, and you can define custom exception classes that carry extra detail.
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not enough money");
}
}The withdraw method needs a balance field; in a real account class it would be stored and maintained by other methods. This snippet focuses on how throw interrupts flow and carries a message. Use exceptions for exceptional situations, not for ordinary flow control such as ending a search loop.
Key Points
- Exceptions interrupt normal flow and must be caught or declared.
- try, catch, and finally provides structure for handling failures.
- Checked exceptions are enforced by the compiler; unchecked ones are not.
- throw raises an error, and custom exception classes can carry extra details.