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

Tuesday 20 July 2010

Test ruby after installation

Sounds silly and obvious, But if we miss to run './rubytest' after installing ruby(any software, especially from source) we might land in big trouble. We might get the feeling that it got installed correctly but it may not. A random check in irb could show something like "123.12".to_f => 123123.0 Which is wrong, But ruby was installed fine.

I got the tests ran successfully later and "123.12".to_f gave me 123.12.