Ruby - catch..throw with exception

Introduction

catch and throw breaks out of a defined block of code when some condition is met.

You could use catch and throw to break out of a block of code when an exception occurs.

For example, this code will exit the block delimited by curly brackets if a ZeroDivisionError occurs:

Demo

catch( :finished) {
   print( 'Enter a number: ' )
   num = gets().chomp.to_i# w ww . jav  a 2s  .c  om
   begin
      result = 100 / num
   rescue Exception => e
      throw :finished        # jump to end of block
   end
   puts( "The result of that calculation is #{result}" )
}     # end of :finished catch block

Result

Related Topic