Tuesday, September 21, 2010

Exception handling in Ruby

The Ruby Exception Handling mechanism includes:

1. rescue and final clauses - for handling unwanted errors and
exit gracefully.

2. raise - for deliberately creating and raising exceptions in
code.

3. catch and throw clause - for continuing execution at some
point up the function call stack


I have been mainly using rescue in my code and have managed to handle most of the exceptions.

Example

i=0
while i<=10
  begin
    if i ==0
      1/0
    end
    raise "random exception"
   rescue ZeroDivisionError
    i+=1
  end
end

Rescuing Exceptions Inside Methods

def  foo_method
  puts "Hi"  raise
  puts "Bye"
rescue
  puts "Rescuing exceptions"

No comments:

Post a Comment