44

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.

Andrew Grimm
  • 70,470
  • 47
  • 186
  • 310
René Nyffenegger
  • 35,550
  • 26
  • 140
  • 232

2 Answers2

60

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.

severin
  • 9,689
  • 1
  • 36
  • 39
56

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
MBO
  • 27,873
  • 5
  • 47
  • 52