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:
My question:
Can I use rescue
in a one-line condition with require
? If yes: how? If no: Why?
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
.
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