A Syntax question..

S

Sonny Chee

Hey Guys,

I would have thought the following two code snippets were equivalent.
However, only the first one will raise err. Can someone explain to me
how I should be 'reading' the 2nd snippet?


rescue Exception => err
begin
RDoc::usage
rescue SystemExit
end
raise err


rescue Exception => err
begin RDoc::usage rescue SystemExit end
raise err


Sonny.
 
D

Dale Martenson

Hey Guys,

I would have thought the following two code snippets were equivalent.
However, only the first one will raise err. Can someone explain to me
how I should be 'reading' the 2nd snippet?

rescue Exception => err
begin
RDoc::usage
rescue SystemExit
end
raise err

rescue Exception => err
begin RDoc::usage rescue SystemExit end
raise err

Sonny.

This may be wrong, but this works:

begin
raise err
rescue Exception => err
begin
puts "bummer 1"
raise err2
rescue Exception => err2
puts "bummer 1.1"
end
end

..vs.

begin
raise err
rescue Exception => err
begin puts "bummer 2"; raise err2; rescue Exception =>err2; puts
"bummer 2.1"; end
end
 
S

Sonny Chee

Thanks Dale. I'm not actually looking for a workaround. Snippet #1 of
my original post does work. I'm trying to understand why snippet #2
doesn't.

The only difference between the two are the whitespaces. If someone
could help me understand how snippet #2 is being parsed/read by the
interpretter that would be super.
 
B

Brian Candler

Hey Guys,

I would have thought the following two code snippets were equivalent.
However, only the first one will raise err. Can someone explain to me
how I should be 'reading' the 2nd snippet?


rescue Exception => err
begin
RDoc::usage
rescue SystemExit
end
raise err


rescue Exception => err
begin RDoc::usage rescue SystemExit end
raise err

These are two different syntactic constructions.

<expression1> rescue <expression2>

returns the value of <expression1>, unless there is an exception in which
case it returns the value of <expression2>

In this construct, you cannot specify the exception class. I think it only
catches StandardError and subclasses.

Typical usage:

foo rescue nil # just ignore StandardError

a = foo rescue bar rescue baz # return value from foo, if exception
# then bar, if exception then baz

Regards,

Brian.
 

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,239
Messages
2,571,200
Members
47,840
Latest member
Tiffany471

Latest Threads

Top