4

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
Freedom_Ben
  • 11,247
  • 10
  • 69
  • 89

1 Answers1

4

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
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • 7
    @RamondeCValle the `rescue` statement modifier only rescues [`StandardError`](http://ruby-doc.org/core-1.9.3/StandardError.html) (and its subclasses). [`LoadError`](http://ruby-doc.org/core-1.9.3/LoadError.html) isn’t a subclass of `StandardError`. – matt Oct 05 '12 at 18:23