How do I rescue from a `require': no such file to load in ruby?

那年仲夏 提交于 2019-11-30 21:25:06

问题


I am trying to rescue from a ``require': no such file to load in ruby` in order to hint the user at specifying the -I flag in case he has forgotten to do so. Basically the code looks like:

begin
  require 'someFile.rb'
rescue
  puts "someFile.rb was not found, have you"
  puts "forgotten to specify the -I flag?"
  exit
end

I have expected the rescue part to take over execution in case someFile.rb was not found, but my assumption was wrong.


回答1:


rescue without arguments rescues only StandardError s. The LoadError (that is raised by a file not found) is not a StandardError but a ScriptError (see http://blog.nicksieger.com/articles/2006/09/06/rubys-exception-hierarchy). Therefore you have to rescue the LoadError explicitly, as MBO indicated.




回答2:


You have to explicitly define which error you want to rescue from.

begin
  require 'someFile.rb'
rescue LoadError
  puts "someFile.rb was not found, have you"
  puts "forgotten to specify the -I flag?"
  exit
end


来源:https://stackoverflow.com/questions/2460891/how-do-i-rescue-from-a-require-no-such-file-to-load-in-ruby

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