Why must LoadError be explicitly caught from require()

B

Ben Harper

Why do I explicitly have to catch LoadError as thrown by 'require'?

The following code demonstrates my problem:
------------------------------------------
begin
require 'not_existent'
rescue
print 'I am never reached'
#rescue LoadError
# print "But uncommenting these lines allows me to handle it"
end
 
J

Jan Svitok

Why do I explicitly have to catch LoadError as thrown by 'require'?

The following code demonstrates my problem:
------------------------------------------
begin
require 'not_existent'
rescue
print 'I am never reached'
#rescue LoadError
# print "But uncommenting these lines allows me to handle it"
end

Because empty 'rescue' clause is the same as 'rescue StandardError',
and LoadError is not its subclass. See [1] for the hierarchy (or it's
in PickAxe as well).

This is documented in rdoc [2]; but don't worry, I overlooked it as well ;-)

[1] http://www.zenspider.com/Languages/Ruby/QuickRef.html#34
[2] http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html#S2:
...If you write a rescue clause with no parameter list, the parameter
defaults to StandardError.
 
K

khaines

Why do I explicitly have to catch LoadError as thrown by 'require'?

The following code demonstrates my problem:
------------------------------------------
begin
require 'not_existent'
rescue
print 'I am never reached'
#rescue LoadError
# print "But uncommenting these lines allows me to handle it"
end
------------------------------------------

Because not throwing an exception would be bad.

What is your alternative?


Kirk Haines
 
K

khaines

Why do I explicitly have to catch LoadError as thrown by 'require'?

The following code demonstrates my problem:
------------------------------------------
begin
require 'not_existent'
rescue
print 'I am never reached'
#rescue LoadError
# print "But uncommenting these lines allows me to handle it"
end
------------------------------------------

Oh, I am sorry. I just work from a nap (long night) and misinterpreted
that.

Because LoadError is not a subclass of StandardError. A plain rescue
catches StandardError and subclasses.


Kirk Haines
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,211
Messages
2,571,092
Members
47,693
Latest member
david4523

Latest Threads

Top