Skip to main content

Command Palette

Search for a command to run...

Code Smell 73 - Exceptions for Expected Cases

Published
1 min read
Code Smell 73 - Exceptions for Expected Cases

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

  1. Use Exceptions just for unexpected situations.

  2. 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

More info

Credits

Photo by Greg Rosenke on Unsplash


When debugging, novices insert corrective code; experts remove defective code.

Richard Pattis


This article is part of the CodeSmell Series.

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.