gpt4 book ai didi

Ruby:如果出现正确的错误,我如何返回一个 bool 值?

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:53 25 4
gpt4 key购买 nike

我有兴趣比较我的代码是否出现了正确的错误。如果引发正确的错误,则返回 true,否则返回 false。

有办法解决吗?还是我需要编写异常处理?

例如,

some_method(arg) == TypeError # => true

最佳答案

When an exception has been raised but not yet handled (in rescue, ensure, at_exit and END blocks) the global variable $! will contain the current exception and $@ contains the current exception’s backtrace.

按以下操作(使用内联 rescue 方式):

2.0.0-p0 :001 > [1, 2, 3].first("two")
TypeError: no implicit conversion of String into Integer
from (irb):1:in 'first'
from (irb):1
from /home/kirti/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in '<main>'
2.0.0-p0 :002 > [1, 2, 3].first("two") rescue $!.class == TypeError
=> true
2.0.0-p0 :003 > [1, 2, 3]['a'] rescue $!.class == TypeError
=> true
2.0.0-p0 :004 > [1, 2, 3]['a']
TypeError: no implicit conversion of String into Integer
from (irb):4:in '[]'
from (irb):4
from /home/kirti/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in '<main>'
2.0.0-p0 :005 > 1/0 rescue $!.class == TypeError
=> false
2.0.0-p0 :006 >

TypeError

Raised when encountering an object that is not of the expected type.

[1, 2, 3].first("two")

raises the exception: TypeError: no implicit conversion of String into Integer

在你的情况下你可以这样写:

some_method(arg) rescue $!.class == TypeError

关于Ruby:如果出现正确的错误,我如何返回一个 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com