2008年4月30日 星期三

error handling: rescue & raise

handle exception:

ex:
begin
      puts  1/0
rescue
     puts "error"
end
--->  "error"

rescue can for specific exception:
ex:
begin
     puts 1/0
rescue  ZeroDivisionError
     puts "error"
end

rescue for method
ex:
def test
    puts "test"
rescue
    puts "rescue"
end
       
raise
raise exception
ex:
def test
   raise  ArgumentError,  "argument error"
end
the second argument is the message printed

get the exception
ex:
rescue ArgumentError =>  e
e is the exception 

define exception
ex:
class  TestException  <>
end

沒有留言: