Exception Handling Best Practices
Writing `try-catch` blocks is easy, but writing good error handling code requires discipline. Here are the top rules to follow.
1. Never Swallow Exceptions
Don't catch an exception and do empty logic. This hides the error forever.
// BAD
catch (Exception e) { }
// GOOD
catch (Exception e) {
e.printStackTrace(); // or Logger.error()
}
2. Catch Specific Exceptions
Always catch the most specific exception first. Don't just catch
Exception for everything.
3. Clean Up Resources
Always use a finally block or "Try-with-Resources" to close files
and connections.
// Try-with-Resources (Java 7+)
// Automatically closes the resource
try (Scanner scanner = new Scanner(new File("test.txt"))) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
4. Don't Catch 'Throwable'
Never catch Throwable because it includes Error (like
OutOfMemoryError) which you shouldn't try to handle.
Output
Click Run to execute your code
Summary
- Log the exception or handle it; never ignore it.
- Use Try-with-Resources for auto-closing.
- Be specific in your catch blocks.
Enjoying these tutorials?