如何检查是否引发了ArgumentError?

时间:2014-04-18 15:47:10

标签: ruby exception-handling

我希望能够检查某行代码是否生成ArgumentError

类似的东西:

if this.ArgumentError?
  puts "there was an error"
else 
  puts "no error"
end

我搜索了文档,但没有发现任何似乎有效的内容。

这可能吗?

1 个答案:

答案 0 :(得分:2)

您必须使用异常处理机制。例如:

begin
  # here is the code that could raise ArgumentError   
rescue ArgumentError
  puts "there was an error"
else
  puts "no error"
end

有关如何处理和引发异常的更多信息,请参阅official documentation