Wednesday, July 11, 2007

Exception handling in Ruby

Like Java, Ruby has the exception handling capabilities.
Handling the any type of exceptions in ruby is pretty simple,
Just use begin rescue pair w/t specifying what kind of exceptions you do want to catch.

begin
code
code
resuce Exception => msg
puts "Something went wrong ("+msg+")"
end

rescue/raise is used to signal error conditions. This is analogous to
Exceptions in Java or C++.

Throw/catch is used to unwind the stack to a desired point. It's like
a labeled break. For example:

catch(:done){
loop {
do_work
if time_to_stop? throw :done
}
}

It's nice because you can break out of arbitrarily nested loops/blocks/etc.

There appear to be 2 separate exception mechanisms in Ruby, catch/throw and
rescue/raise/retry. Is this right?

Not really. A throw just lets one unwind from some deep nesting without
generating a back trace, passing some value along to the catch.

It is much faster and lighter weight than the exception mechanism, and should
be used for cases where a fast, lightweight escape from some deep place is
wanted, perhaps with some passing of data from the deep place to the shallow
place, but where an actual exception isn't needed.

No comments: