Monday 25 October 2010

exception handling in ruby

Normally we don't explicitly specify the Exception type while 'rescue' ing it. ex:
begin
  raise 'alert'
rescue => e
  p "Error"
end
=> Error
Everything is fine here, But look at another case,
begin
  require 'IamNotThere'
rescue => e
  p "Error"
end
=> LoadError: no such file to load -- IamNotThere
Never expected ?, Our rescue block didn't handle this case.
begin
  require 'IamNotThere'
rescue Exception=> e
  p "Error"
end
=> Error
Again, everything is safe here.

So, It's always better narrow down our expectation or use 'Exception => e'. Default is 'StandardError'.


Heirarchy:

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