Code Smell 288 — Unthrown Exceptions | by Maximiliano Contieri
When you forget to throw, your code will blow. When you create a new exception but forget to throw it, your code might appear to work correctly, but it silently ignores critical errors.
Importance of Throwing Exceptions
Creating exceptions is similar to creating business objects, and constructors should not have side effects. Unless you throw them, it becomes dead code.
You can detect this smell by reviewing your code for instances where you create exceptions but do not raise them. Automated linters and static analyzers can flag such issues.
Real-world Failures
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. Proper error handling and good coverage ensure your code behaves predictably and reliably.
AI-generated Code and Exceptions
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-based linters can detect this smell by analyzing unreferenced exception instances.
Fixing it requires proper domain knowledge to decide where to throw the exception. Always throw exceptions immediately after you create them.
Conclusion
Silent failures can lead to significant issues in your code, making it harder to maintain and debug. It is essential to handle exceptions correctly to maintain code integrity.
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. Coding tutorials and news can be found on the developer homepage gitconnected.com, skilled.dev, and levelup.dev.










