Java Exception Anti-Patterns

Achieve Efficient Maintainable and Simple Java Exception handling killing those anti-patterns.

Gaetano Piazzolla
3 min read1 day ago
Photo by Andrew Palmer on Unsplash

The Silencer

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignoring the exception
}

This anti-pattern is everywhere. It’s mostly added in the codebase when fixing a compiler error without using Throws. It makes the JVM scream into a pillow. As a rule of thumb, never catch an exception without logging it, wrapping it, or re-throwing it to the upper level.

The Exceptional Else Block

AKA Coding by Exception. This is opinionated. The definition of exception is: someone or something that is not included in a rule, group, or list or that does not behave in the expected way.

public void processFile(String fileName) {
try {
File file = new File(fileName);
// Some operation that might throw FileNotFoundException
FileReader fileReader = new FileReader(file);
} catch (FileNotFoundException e) {
// This is the exceptional else block
log.info("File not found, creating a new one.");
createNewFile(fileName);
}
}

IMHO It is wrong to consider the case in which the Exception is thrown as a…

--

--