TL;DR: Creating a new exception without throwing it leads to silent failures.

When You Forget to Throw, Your Code Will Blow 💣💥

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

Without Proper Instructions With Specific Instructions
ChatGPT ChatGPT
Claude Claude
Perplexity Perplexity
Copilot Copilot
Gemini Gemini
DeepSeek DeepSeek
Meta AI Meta AI

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 👩‍❤️‍💋‍👨

Code Smell 165 - Empty Exception BlocksMaxi Contieri ・ Sep 24 '22#webdev #beginners #programming #pythonCode Smell 26 - Exceptions PollutingMaxi Contieri ・ Nov 16 '20#oop #exceptions #tutorial #programmingCode Smell 142 - Queries in ConstructorsMaxi Contieri ・ Jun 20 '22#oop #java #programming #databaseCode Smell 09 - Dead CodeMaxi Contieri ・ Oct 28 '20#codenewbie #tutorialCode Smell 132 - Exception Try Too BroadMaxi Contieri ・ May 18 '22#python #programming #cleancode #webdevCode Smell 73 - Exceptions for Expected CasesMaxi Contieri ・ May 31 '21#webdev #codenewbie #cleancode #oop

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

Software Engineering Great QuotesMaxi Contieri ・ Dec 28 '20#codenewbie #programming #quotes #software

This article is part of the CodeSmell Series.

Read full article