Gyepi Sam
2010-07-13
Throw and Catch in Ruby

C++, Java, and Javascript use the throw, catch idiom to propagate errors, in the form of exceptions, up stack frames.

Ruby uses raise and rescue for the the same purpose. However, Ruby also has the throw, catch, which are also used to propagate information, but not necessarily exceptions up the stack frame.

Similar to Common Lisp’s exception and condition handling system, this dual, parallel mechanism allows one to handle exceptions, that is unexpected results in the program, with raise and rescue and use catch and throw for instances where data flow across stack frames.

throw and catch are a powerful way to handle unexpected results in a program at higher stack levels than where the error occurs. It allows either for centralized error or exception handling as well as handling by code that may be better able to understand and handle the problem. Clearly the ability to propagate data across stack frames is a useful one.

However, Java and Javascript only support the use of exceptions for this idiom. Once could argue, of course, that with the use of named exceptions, they do not need another mechanism. C++, of course, supports exceptions and additionally inherits setjmp and longjmp from C which is generally the underlying mechanism for exception handling.