Skip to main content

Command Palette

Search for a command to run...

Code Smell 288 - Unthrown Exceptions

When You Forget to Throw, Your Code Will Blow πŸ’£πŸ’₯

Updated
β€’3 min read
Code Smell 288 - Unthrown Exceptions
M

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

TL;DR: Creating a new exception without throwing it leads to silent failures. πŸ‘ƒπŸ’©

Problems πŸ˜”

  • Silent failures
  • Unhandled errors
  • Misleading logic
  • Hidden defects
  • Hollow Exceptions

Solutions πŸ˜ƒ

  1. Always ensure you throw exceptions
  2. Check exception usage and catching
  3. Test exception paths
  4. Use linters
  5. Avoid creating unused exceptions

Context πŸ’¬

When you create a new exception but forget to throw it, your code might appear to work correctly, but it silently ignores critical errors.

Creating exceptions is the same as creating business objects and constructors should not have side effects.

Unless you throw them, it is dead code.

Sample Code

Wrong 🚫

class KlendathuInvasionError(Exception):
    def __init__(self, message):
        self.message = message
    # This is a hollow exception        

def deploy_troops(safe):
    if not safe:
        KlendathuInvasionError("Drop zone is hot!")  
        # Never thrown
    print("Troopers deployed.")

deploy_troops(False)

Right πŸ‘‰

class KlendathuInvasionError(Exception):
    def __init__(self, message):
        super().__init__(message)

def deploy_troops(safe):
    if not safe:
        raise Exception("Drop zone is hot!")
    # You throw the exception
    print("Troopers deployed.")

try:
    deploy_troops(False)
except KlendathuInvasionError as e:
    print(f"Abort mission: {e}")
    # You handle the exception

Detection πŸ”

You can detect this smell by reviewing your code for instances where you create exceptions but do not raise them.

You can also search for instances where an exception is instantiated but never raised.

Automated linters and static analyzers can flag such issues.

Tags 🏷️

  • Exceptions

Level πŸ”‹

[X] Beginner

Why the Bijection Is Important

An exception represents a real-world failure inside your program.

If you create an exception but never throw it, your code lies about the presence of an error.

When you fail to throw an exception, you break the one-to-one correspondence between the real-world problem and its coding representation.

AI Generation πŸ€–

AI generators might create this smell if they generate exception-handling code without ensuring that exceptions are properly raised.

Always review AI-generated code for proper error handling.

AI Detection 🦾

AI-based linters can detect this smell by analyzing unreferenced exception instances.

Fixing it requires proper domain knowledge to decide where to throw the exception.

Try Them! πŸ›ž

Remember: AI Assistants make lots of mistakes

Conclusion βœ”οΈ

Always throw exceptions immediately after you create them.

Silent failures can lead to significant issues in your code, making it harder to maintain and debug.

Proper error handling and good coverage ensure your code behaves predictably and reliably.

Relations πŸ‘©β€β€οΈβ€πŸ’‹β€πŸ‘¨

Disclaimer πŸ“˜

Code Smells are my opinion.

Credits πŸ™

Photo by Bethany Reeves on Unsplash


Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases.

Norman Augustine


This article is part of the CodeSmell Series.

Code Smells

Part 30 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.

Up next

Code Smell 287 - Unused Local Assignment

Are you using the returned value?