DEV Community

Cover image for Code Smell 73 - Exceptions for Expected Cases
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

4 3

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
Enter fullscreen mode Exit fullscreen mode

Right

for (int index = 0; index < array.length; index++)
        array[index]++;

//index < array.length breaks execution
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay