Exceptions are a great way of separating happy path versus trouble path. But we tend to over-complicate our solutions.
TL;DR: Don't nest Exceptions. Nobody cares of what you do in the inner blocks.
Problems
- Readability
Solutions
- Refactor
Sample Code
Wrong
try {
transaction.commit();
} catch (e) {
logerror(e);
if (e instanceOf DBError){
try {
transaction.rollback();
} catch (e) {
doMoreLoggingRollbackFailed(e);
}
}
}
//Nested Try catchs
//Exception cases are more important than happy path
//We use exceptions as control flow
Right
try {
transaction.commit();
} catch (transactionError) {
this.withTransactionErrorDo(transationError, transaction);
}
//transaction error policy is not defined in this function
//so we don't have repeated code
//code is more readable
//It is up to the transaction and the error to decide what to do
Detection
We can detect this smell using parsing trees.
Tags
- Exceptions
Conclusion
Don't abuse exceptions, don't create Exception classes no one will ever catch, and don't be prepared for every case (unless you have a good real scenario with a covering test).
Happy path should always be more important than exception cases.
Relations

Code Smell 73 - Exceptions for Expected Cases
Maxi Contieri ⭐⭐⭐ ・ May 31 '21 ・ 2 min read

Code Smell 26 - Exceptions Polluting
Maxi Contieri ⭐⭐⭐ ・ Nov 16 '20 ・ 2 min read
More Info
Credits
Photo by David Clode on Unsplash
Thanks to @Rodrigo for his inspiration
✍️ Clean code tip
Extract try/catch
Separate logic from how we handle its exceptions. The use of multiple try/catch obscure the intent of the code, so it's better to keep them separated to make the code readable
Look how improved the code in the second picture
#cleancode14:32 PM - 11 Jun 2021
Writing software as if we are the only person that ever has to comprehend it is one of the biggest mistakes and false assumptions that can be made.
Karolina Szczur

Software Engineering Great Quotes
Maxi Contieri ⭐⭐⭐ ・ Dec 28 '20 ・ 13 min read
This article is part of the CodeSmell Series.
Top comments (0)