Search code examples
crubyexceptionruby-c-extensionrescue

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


Solution

  • 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; }