cover-img

Code Smell 73 - Exceptions for Expected Cases

26 May, 2023

1

1

0

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

Code Smell 72 - Return Codes

Code Smell 26 - Exceptions Polluting

More Info

Credits

Photo by Greg Rosenke on Unsplash


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

Richard Pattis

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

1

1

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.