I come from a C# background where I usually re-raise exceptions with the original exception contained inside the parent exception. Is a similar concept available in Ruby? How do I detect and raise an exception while maintaining the context of the lower level exception?
Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).
When you raise an exception in Ruby, the world stops and your program starts to shut down. If nothing stops the process, your program will eventually exit with an error message. Here's an example. In the code below, we try to divide by zero.
catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object.
The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.
Take a look at the tricks from the talk Exceptional Ruby by Avdi Grimm:
class MyError < StandardError
attr_reader :original
def initialize(msg, original=nil);
super(msg);
@original = original;
end
end
# ...
rescue => error
raise MyError.new("Error B", error)
end
Ruby 2.1 added Exception#cause feature to solve this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With