Exceptions are handy Gotos and flags. Let's abuse them.
TL;DR: Do not use exceptions for flow control.
Problems
Readability
Principle of least astonishment Violation.
Solutions
Use Exceptions just for unexpected situations.
Exceptions handle contract violations. Read the contract.
Sample Code
Wrong
try {
for (int i = 0;; i++)
array[i]++;
} catch (ArrayIndexOutOfBoundsException e) {}
//Endless loop without end condition
Right
for (int index = 0; index < array.length; index++)
array[index]++;
//index < array.length breaks execution
Detection
This is a semantic smell. Unless we use machine learning linters it will be very difficult to find the mistakes.
Tags
- Readability
Conclusion
Exceptions are handy, and we should definitively use them instead of returning codes.
The boundary between correct usage and wrong usage is blur like so many design principles.
Relations
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Code Smell 26 - Exceptions Polluting
Maxi Contieri ・ Nov 16 '20
More info
Credits
Photo by Greg Rosenke on Unsplash
When debugging, novices insert corrective code; experts remove defective code.
Richard Pattis
![mcsee](https://res.cloudinary.com/practicaldev/image/fetch/s--by_E26Wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://res.cloudinary.com/practicaldev/image/fetch/s--XvnZDWAZ--/c_fill%2Cf_auto%2Cfl_progressive%2Ch_150%2Cq_auto%2Cw_150/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/366059/69feb7c3-ab01-4bcd-a6f5-ec38e9300da3.jpeg)
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)