What you prefer when it comes to rescue? Rescue the specific exception, not every exception!
There are two scenarios:
1. Where you know what type of error can be thrown by a piece of code that you write.
2. When you cannot say the type of error OR a class of that error OR the situation is unknown for instance, network timeout. Also, it applies when you’re not raising any error specifically, but still wants to rescue the exception because you know that code might throw errors.
The Default is StandardError
Choose it in the second scenario. By default,
rescueonly catches things that are
StandardErrorThat means when you don’t pass any class Ruby considers it as a StandardError. — It’s a default.
# your world! I meant your code :) which can be crashed💥 any moment.
rescue => e
# This rescue all the basic exception.
endOR - Both are identical & it's defaultbegin
# your code
rescue StandardError => e
# put logger to know the error
Rescuing Specific Errors/Exceptions
Choose it when you know the specific error type and Exception class to rescue it. Find out the exception class hierarchy from here!
# Single exception
rescue ArgumentError => e
// This will only rescue StandardError::ArgumentError exceptions
end# Multiple exceptions
rescue ArgumentError, TypeError => e
// your code
// This will rescue both exceptions
Rescue with specific exception class is always a better choice and a better approach to protect/save your Ruby world!
Happy Coding!! — Rubyist