Does the Ruby rescue statement work with require?

2019-05-10 01:10发布

Does the Ruby rescue statement modifier work with require?

irb(main):001:0> require 'a' rescue nil
LoadError: no such file to load -- a
    from (irb):1:in `require'
    from (irb):1
    from :0

1条回答
做自己的国王
2楼-- · 2019-05-10 01:47

You can rescue from a LoadError you just need to use the begin/end style and not use the inline rescue:

This works as you expect:

begin
 require 'a'
rescue LoadError => ex
 puts "Load error: #{ex.message}"
end
查看更多
登录 后发表回答