The rule “Do not rescue the Exception class” is a crucial practice in Ruby programming for handling exceptions. The Exception class is the root of Ruby’s exception hierarchy, so when you rescue Exception, you’re potentially catching and handling severe system errors that Ruby itself is trying to bubble up. These could be fundamental issues like memory overflows and syntax errors, which could cause the program to behave unexpectedly or even crash.
Rescuing the Exception class can lead to major problems in debugging since it can hide the true nature of the error and its source. It makes it harder to pinpoint where and why the error occurred. This can lead to significant delays in identifying and resolving coding issues.
Instead of rescuing the Exception class, it is better to rescue more specific error classes or use StandardError which is the superclass for most error types. For instance, if you’re expecting possible nil values, use rescue NoMethodError. This allows Ruby to handle severe system errors appropriately and ensures that you’re only rescuing the errors you expect. This practice makes your code safer, more predictable, and easier to maintain and debug.
Non-Compliant Code Examples
begin# The exit will be rescued, so the program won't exit.exitrescueException# You are here!endbegin# The exit will be rescued, so the program won't exit.exitrescueException=>e# You are still here!end
Compliant Code Examples
beginexitrescueStandardError# Not reachedendbeginexitrescueStandardError=>e# Not reached eitherendbeginexitrescue=>e# Equivalent to the above.# Does not rescue Exception, but StandardError.end
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- ruby-best-practices # Rules to enforce Ruby best practices.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines