ruby rescue

23 Nov 2009

ruby的异常处理和java很相似

begin
  ...
rescue
  ...
end

rescue默认只会接受StandardError

irb(main):001:0> begin
irb(main):002:1* 1 / 0
irb(main):003:1> rescue
irb(main):004:1> puts "divide 0"
irb(main):005:1> end
divide 0

但是像SyntaxError并不是继承StandardError的,就无法被resuce

irb(main):001:0> begin
irb(main):002:1* eval("1 +")
irb(main):003:1> rescue
irb(main):004:1> puts "syntax error"
irb(main):005:1> end
SyntaxError: (eval):1:in `irb_binding': compile error
(eval):1: syntax error, unexpected $end
   from (irb):2
   from (irb):2
   from :0

这种情况必须指定相应的Error或者是所有异常的基类Exception

irb(main):001:0> begin
irb(main):002:1* eval("1 +")
irb(main):003:1> rescue Exception
irb(main):004:1> puts "syntax error"
irb(main):005:1> end
syntax error

最后附上Exception Hierarchy

Exception
 NoMemoryError
 ScriptError
   LoadError
   NotImplementedError
   SyntaxError
 SignalException
   Interrupt
 StandardError
   ArgumentError
   IOError
     EOFError
   IndexError
   LocalJumpError
   NameError
     NoMethodError
   RangeError
     FloatDomainError
   RegexpError
   RuntimeError
   SecurityError
   SystemCallError
   SystemStackError
   ThreadError
   TypeError
   ZeroDivisionError
 SystemExit
 fatal

Tags 


blog comments powered by Disqus