catch
in Ruby is meant to jump out of deeply nested code. In Java e.g. it is possible to achieve the same with Java's try-catch
meant for handling exceptions, it is however considered poor solution and is also very inefficient. In Ruby for handling exceptions we have begin-raise-rescue
and I assume it is also to expensive to use it for other tasks.
Is Ruby's catch-throw
really a more efficient solution then begin-raise-rescue
or are there any other reasons to use it to break nested blocks instead of begin-raise-rescue
?
Josh's answer is correct. I want to add more information about
catch-throw
andraise-rescue
.catch-throw
is used for flow control whereasraise-rescue
is used for exception/error handling. The different is:backtrace
is not needed forcatch-throw
(flow control). Trust me, the main reason causesraise-rescue
runs slow thancatch-throw
10 times in Josh's gist israise-rescue
takes a lot time to createbacktrace
object.If you want to
raise
without backtrace, use syntax:Checkout my gist.
raise without backtrace
is much faster thanraise with backtrace
.April 2016 Update:
I've updated my gist:
In addition to being the "correct" way to get out of control structures,
catch-throw
is also significantly faster(10 times as fast in my testing). Check out this gist for my code and results.