Rohini Pamarty
Joined: 12 May 2011 Posts: 53
|
Posted: Thu May 26, 2011 10:33 am Post subject: rescue-raise VS catch-throw in Ruby |
|
|
rescue and raise
_________________
In Ruby, exceptions are packaged into objects of class Exception or one of Exception’s many subclasses.Ruby can raise exceptions automatically when incorrect functions are performed, and can raise exceptions from code too which can be done using the "raise" method and by using an existing exception class, or by creating a new own that inherits from the existing Exception class.
In most situations, stopping a program because of a single error isn’t necessary. In Ruby, the "rescue" clause is used, along with begin and end, to define blocks of code to handle exceptions.
Consider the following code
class Alphabet_exception < RuntimeError
end
begin
puts "Enter a number"
num=gets.chomp
raise Alphabet_exception,"Enter only numbers" if num.match(/[a-z]/)
num=num.to_i
raise ZeroDivisionError,"Number should not be zero" if num==0
puts "value after division is #{(10/num.to_f)}"
rescue =>e
puts e
retry
end
catch and throw
___________________
Sometimes to be able to break out of a thread of execution during normal operation in a similar way to an exception, but without actually generating an error. Ruby provides two methods, catch and throw, for this purpose.
Consider following code:
catch(:finish) do
puts "enter a number"
num=gets.chomp.to_i
15.times do |x|
y = x*num
puts y
throw :finish if y == 30
end
puts "Generated numbers without 30"
end
Within the catch block numbers are generated and displayed, and if number is ever 30, control gets escape out of the block using throw :finish.
Basic difference between catch-throw and rescue-raise are
1)catch and throw are designed to be used in situations where no error has occurred, but being escaped from nested loop, method call, or similar.
2)catch and throw work with symbols rather then exceptions. As in above example ":finish" is a symbol used, whereas for rescue and raise "RuntimeError" and "ZeroDivisionError" Exception classes are used.
Thanks
Rohini |
|