【问题标题】:Ruby c extensions: How can I catch all exceptions, including things that aren't StandardErrors?Ruby c 扩展:如何捕获所有异常,包括非标准错误?
【发布时间】:2011-03-14 02:32:10
【问题描述】:

在红宝石中,

begin
  # ...
rescue
  # ...
end

不会捕获不是StandardError 子类的异常。在 C 语言中,

rb_rescue(x, Qnil, y, Qnil);

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

会做同样的事情。如何从 ruby​​ C 扩展中rescue Exception => e(而不仅仅是rescue => e)?

【问题讨论】:

    标签: c ruby exception-handling ruby-c-extension rescue


    【解决方案1】:

    Ruby 需要更多文档。我不得不进入 ruby​​ 源代码,这就是我发现的:

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

    所以,我的问题的答案(我猜)是:

    rb_rescue2(x, Qnil, y, Qnil, rb_eException, (VALUE)0);
    
    VALUE x(void) { /* ... */ return Qnil; }
    VALUE y(void) { /* ... */ return Qnil; }
    

    【讨论】:

    • +1 刚刚遇到同样的问题,这个发现解决了我的问题。
    • 我会投赞成票,但不清楚什么回调做什么。救援时会叫什么?救出什么?
    • 我假设b_procbegin 语句之后的代码,r_proc 是救援代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    • 2011-08-20
    • 1970-01-01
    • 2013-06-12
    • 2011-11-09
    • 1970-01-01
    相关资源
    最近更新 更多