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

1

6

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

Interpret answered 9/7, 2010 at 21:48 Comment(0)
I
5

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; }
Interpret answered 9/7, 2010 at 22:23 Comment(3)
+1 Just hit the same problem and this discovery resolved my problem.Libidinous
I would vote this up, but am not clear on what callbacks do what. What gets called in the event of a rescue? What is being rescued?Rasmussen
I would assume b_proc is the code after the begin statement, and r_proc is the rescue code.Aviculture

© 2022 - 2024 — McMap. All rights reserved.