How to handle exceptions
Catch a specific exception
Put risky code in try and catch only exceptions the program can handle meaningfully.
try {
int number = Integer.parseInt("abc");
System.out.println(number);
} catch (NumberFormatException error) {
System.out.println("Enter a whole number.");
}
Use finally
A finally block runs whether the try succeeds or throws, making it suitable for necessary cleanup.
try {
System.out.println("Working");
} finally {
System.out.println("Cleanup");
}
Throw an exception
Reject invalid arguments close to the method boundary and include a useful message.
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("age cannot be negative");
}
}
Do not hide failures
- Catch the most specific useful exception type.
- Do not leave catch blocks empty.
- Log or display enough context to understand the failure.
- Use try-with-resources for closeable files and streams.