Ruby ignores rescue ArgumentError

為{幸葍}努か 提交于 2019-12-05 04:29:03

The exception is not thrown inside the function, but at the point where it is called, so you need to catch it somewhere else:

def divide(a, b)
  a.to_s + ' divided by ' + b.to_s + ' is ' + (a/b).to_s
end

begin
  divide(4)
rescue ArgumentError
  puts 'there must be two arguments'
end

While that works, catching ArgumentError is a very bad idea, as it indicates an error in your code which you shouldn't be able to recover from.

The rescue-ing will be done for this part of code : a.to_s + ' divided by ' + b.to_s + ' is ' + (a/b).to_s. Your exception is triggered not in the method, but at calling-time, if you see what I mean.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!