简体   繁体   English

如何弄清楚Ruby中要捕获的异常

[英]How to figure out what exception to catch in Ruby

I was given some code that keeps getting an exception raised from a jRuby library. 我得到了一些代码,不断从jRuby库中获取异常。 The code only handles certain exceptions but it misses the one I keep getting. 代码只处理某些异常,但它错过了我一直得到的异常。

Is there a way I can figure out how to capture that specific exception without digging into the Library code? 有没有办法我可以弄清楚如何在不深入图书馆代码的情况下捕获特定的异常?

At the point where your exception causes the program to exit, you should be shown the type of exception being raised. 在您的异常导致程序退出的时候,你应该显示正在引发异常的类型。

For example, I've bolded the type of exception as reported by IRB in the following example: 例如,我在下面的示例中粗略化了IRB报告的异常类型:

irb(main):001:0> def do_it(a,b); irb(main):001:0> def do_it(a,b); end; 结束; do_it(3,4,5) do_it(3,4,5)
ArgumentError : wrong number of arguments (given 3, expected 2) ArgumentError参数数量错误(给定3,预期2)
from (irb):1:in `do_it' 来自(irb):1:在`do_it'中
from (irb):1 来自(irb):1
from /Users/meagar/.rbenv/versions/2.3.1/bin/irb:11:in `' 来自/Users/meagar/.rbenv/versions/2.3.1/bin/irb:11:in`'

Based on this, I would know I needed to handle ArgumentError . 基于此,我知道我需要处理ArgumentError

Failing that, you can catch all exceptions, use a debugger in your exception handler to inspect the caught exception and figure out its type, and then replace the catch-all with the correct exception type. 如果失败了,您可以捕获所有异常,在异常处理程序中使用调试器来检查捕获的异常并找出其类型,然后用正确的异常类型替换catch-all。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM