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.
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.
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.
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.
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!'
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With