DEV Community

Cover image for Refactoring 004 - Remove Unhandled Exceptions
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

5 1

Refactoring 004 - Remove Unhandled Exceptions

Creating YAGNI exception classes pollutes our environment. Let's remove them.

TL;DR: Remove unnecessary and not references empty exception classes.

Problems Addressed

  • Empty Classes

  • Namespace Polluted

Related Code Smells

Steps

  1. Check there are no references to the empty exception class.

  2. 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


Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Type

[X] Automatic

If the Exception class has no references we can perform a Safe Remove and replace it with Exception class.

Why the code is better?

  • We remove an empty class nobody uses.

  • We shrink the code

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.

Tags

  • Clean up

Related Refactorings

  • Safe Remove

Credits

Image by danielkirsch from Pixabay


This article is part of the Refactoring Series.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay