This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the exceptions category.
Last Updated: 2024-11-21
This is dangerous
begin
do_something
# !! Don't do this
rescue Exception => e
end
Why? This rescues all exceptions that inherit from Exception
. Some of these
are needed internally by Ruby - e.g. NoMemoryError
(out of RAM) or
SignalException::Interrupt
(now you can't Control-C)
This is bad, bad, bad.
Therefore the most extreme level of rescuing you should go to (and the base for your custom exceptions) should be StandardError
instead.
e.g. this is totally acceptable
begin
do_something
rescue StandardError => e
# Only your app's exceptions are swallowed. Things like SyntaxError are left alone.
end
Example exceptions that inherit from StandardError
TypeError
- e.g. what you'd get if you did 4 + "apple"
NoMethodError
- no method