Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - re-raise exception with sub-exception

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?

like image 982
Nippysaurus Avatar asked Dec 05 '11 09:12

Nippysaurus


People also ask

How do you raise exceptions in Ruby?

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

Does raising an error stop execution Ruby?

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.

What is the difference between throw catch and raise rescue?

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.

What happens if in a begin rescue block the rescue code has an error?

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.


2 Answers

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
like image 85
Henrik Avatar answered Sep 18 '22 16:09

Henrik


Ruby 2.1 added Exception#cause feature to solve this problem.

like image 43
Aliaksei Kliuchnikau Avatar answered Sep 20 '22 16:09

Aliaksei Kliuchnikau