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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay