Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby c extensions: How can I catch all exceptions, including things that aren't StandardErrors?

In ruby,

begin
  # ...
rescue
  # ...
end

won't catch exceptions that aren't subclasses of StandardError. In C,

rb_rescue(x, Qnil, y, Qnil);

VALUE x(void) { /* ... */ return Qnil; }
VALUE y(void) { /* ... */ return Qnil; }

will do the same thing. How can I rescue Exception => e from a ruby C extension (instead of just rescue => e)?

like image 912
Adrian Avatar asked Jul 09 '10 21:07

Adrian


People also ask

How do you rescue exceptions in Ruby?

In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from. Note: When using raise without specifying an exception class, Ruby will default to RuntimeError .

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.

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

What is rescue E?

rescue Exception => e # ... end. Using the above begin-rescue block will rescue every exception and error that is raised, from interrupts to syntax errors, and even memory errors, so use it sparingly and with caution.


1 Answers

Ruby needs more documentation. I had to go into the ruby source code, and this is what I found:

VALUE
rb_rescue(VALUE (* b_proc)(ANYARGS), VALUE data1,
      VALUE (* r_proc)(ANYARGS), VALUE data2)
{
    return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError,
              (VALUE)0);
}

So, the answer to my question (i guess) would be:

rb_rescue2(x, Qnil, y, Qnil, rb_eException, (VALUE)0);

VALUE x(void) { /* ... */ return Qnil; }
VALUE y(void) { /* ... */ return Qnil; }
like image 95
Adrian Avatar answered Sep 29 '22 11:09

Adrian