Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using single line conditional with require/rescue

I want to avoid an error, if a require is not successfull.

I can do it with:

begin
  require 'unexisting_script' 
rescue LoadError
end

I tried to do the same with a one-line condition:

require 'unexisting_script' rescue LoadError

and get the error no such file to load -- unexisting_script (LoadError)

With other exceptions/commands I have no problem with a one line rescue, this works:

1 / 0 rescue ZeroDivisionError

I also tried to bracket the command, but withous success:

(require 'unexisting_script') rescue LoadError

I can put everything in one line with ;:

begin require 'unexisting_script'; rescue LoadError; end

but I'm still wondering, why the shortest version does not work.

I found some related questions, but none of them is mentioning a problem with require and rescue:

  • Why does this rescue syntax work?
  • How does one use rescue in Ruby without the begin and end block

My question:

Can I use rescue in a one-line condition with require? If yes: how? If no: Why?

like image 408
knut Avatar asked Nov 12 '13 08:11

knut


1 Answers

You cannot specify the error class when you use rescue in postfix/oneliner notation. What rescue LoadError or rescue ZeroDivisionError means is that it will rescue a (subclass of) StandardError, and in such case, evaluate LoadError or ZeroDivisionError, which has no effect. Since ZeroDivisionError is a subclass of StandardError, it was captured, but LoadError is not, and it was not captured.

By the way, I cannot think of a use case where you want to not raise an error when a required file does not exist. Required files are dependencies, and if requiring them fails, then the program will not work correctly anyway. I feel a code smell in what you are doing. When failure of loading a file does not mess the program, that is usually when you should be using load instead of require.

like image 112
sawa Avatar answered Oct 26 '22 07:10

sawa