Why must LoadError be explicitly caught from require()

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
------------------------------------------

I am running 1.8.4 on Windows.

--
Posted via http://www.ruby-forum.com/.

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 :wink:

[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.

···

On 8/30/06, Ben Harper <rogojin@gmail.com> wrote:

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
------------------------------------------

I am running 1.8.4 on Windows.

Because not throwing an exception would be bad.

What is your alternative?

Kirk Haines

···

On Wed, 30 Aug 2006, Ben Harper wrote:

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

···

On Wed, 30 Aug 2006, Ben Harper wrote:

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 LoadError is not a subclass of StandardError. A plain rescue
catches StandardError and subclasses.

Kirk Haines

Thanks!

···

--
Posted via http://www.ruby-forum.com/.