Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 543
René Nyffenegger Avatar asked Mar 17 '10 09:03

René Nyffenegger


People also ask

How do I use require in Ruby?

The require method takes the name of the file to require, as a string, as a single argument. This can either be a path to the file, such as ./lib/some_library. rb or a shortened name, such as some_library. If the argument is a path and complete filename, the require method will look there for the file.

How does rescue work in Ruby?

The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.

What is begin rescue in Ruby?

Similar to PHP's try-catch, Ruby's exception handling begins with the begin-rescue block. In a nutshell, the begin-rescue is a code block that can be used to deal with raised exceptions without interrupting program execution.

How Exception handling is performed in Ruby?

Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception. puts 'This is Before Exception Arise!'


2 Answers

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.

like image 173
severin Avatar answered Sep 19 '22 14:09

severin


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 
like image 36
MBO Avatar answered Sep 21 '22 14:09

MBO