Refactoring 004 — Remove Unhandled Exceptions
Creating YAGNI exception classes pollutes our environment. Let’s remove them.

Creating YAGNI exception classes pollutes our environment. Let's remove them.
TL;DR: Remove unnecessary and unreferenced empty exception classes.
Problems Addressed 😔
Empty Classes
Namespace Polluted
Related Code Smells 💨
Code Smell 26 - Exceptions Polluting
Steps 👣
Check there are no references to the empty exception class.
Replace the throw sentence with a generic one.
Sample Code 📖
Before 🚨
class RangeNotSatisfiedException < StandardError
end
begin
raise RangeNotSatisfiedException.new
"Range must be betweet 0 and 10"
rescue RangeNotSatisfiedException => e
puts e.message
puts e.exception_type
end
After 👉
# 1. Check there are no references to the empty exception class.
# 2. Replace the throw sentence with a generic one.
begin
raise StandardError.new "Range must be betweet 0 and 10"
rescue StandardError => exception
puts exception.message
puts exception.exception_type
end
Type 📝
[X] Automatic
If the Exception class has no references, you can perform a Safe Remove and replace it with Exception class.
Safety 🛡️
Unless you use metaprogramming, checking for references should be safe enough.
Why is the Code Better? ✨
You remove an empty class that nobody uses.
You shrink the code.
How Does it Improve the Bijection? 🗺️
You remove noise that breaks the 1:1 relationship between concepts and code.
Each class should represent something meaningful.
An unused exception pretends there's a case that never occurs. It lies.
By deleting it, you align your code more closely to the truth.
Now, each exception you see signals a real event, not a hypothetical one.
Limitations ⚠️
If we need to declare an empty exception class as documentation for an API module, our clients might need to catch it.
This is a gold plating and YAGNI example.
Refactor with AI 🤖
Suggested Prompt: 1. Check there are no references to the empty exception class.2. Replace the throw sentence with a generic one.
Without Proper Instructions 📵
With Specific Instructions 👩🏫
Tags 🏷️
Clean up
Level 🔋
[X] Beginner
Related Refactorings 🔄
Refactoring 021 - Remove Dead Code
TL;DR: Eliminate unused functions, constants, and "just-in-case" code.
Credits 🙏
Image by danielkirsch on Pixabay
This article is part of the Refactoring Series
How to Improve your Code With easy Refactorings
Refactorings are amazing to grow and improve our code