Ruby - Catch and Throw

Introduction

catch and throw work with symbols rather than exceptions.

They're used to escape from a nested loop, method call, or similar.

The following example creates a block using catch.

The catch block with the :finish symbol as an argument will immediately terminate and move on to any code after that block if throw is called with the :finish symbol.

Demo

catch(:finish) do 
  1000.times do #  w ww . ja  v  a 2s  . c  om
    x = rand(1000) 
    throw :finish if x == 123 
  end 

  puts "Generated 1000 random numbers without generating 123!" 
end

Within the catch block you generate 1,000 random numbers.

If the random number is ever 123, you escape out of the block using throw :finish.

catch and throw don't have to be directly in the same scope.

throw works from methods called from within a catch block:

Demo

def generate_random_number_except_123 
  x = rand(1000) # from   w ww  .j  a  va  2 s .  c o m
  throw :finish if x == 123 
end 

catch(:finish) do 
  1000.times { generate_random_number_except_123 } 
  puts "Generated 1000 random numbers without generating 123!" 
end

When throw can't find a code block using :finish in its current scope, it jumps back up the stack until it can.

Related Topics