Ruby's Exception Hierarchy

Posted by Nick Sieger Wed, 06 Sep 2006 20:16:00 GMT

Tim Bray:

Today I needed to know the class hierarchy under Exception, and maybe it’s there online but I couldn’t find it. Blecch. Hint: Pickaxe, 2nd ed., page 462.

Well, you could always use Ruby itself, too, that way you’ll always have an up-to-date list:

exceptions = []
tree = {}
ObjectSpace.each_object(Class) do |cls|
  next unless cls.ancestors.include? Exception
  next if exceptions.include? cls
  next if cls.superclass == SystemCallError # avoid dumping Errno's
  exceptions << cls
  cls.ancestors.delete_if {|e| [Object, Kernel].include? e }.reverse.inject(tree) {|memo,cls| memo[cls] ||= {}}
end

indent = 0
tree_printer = Proc.new do |t|
  t.keys.sort { |c1,c2| c1.name <=> c2.name }.each do |k|
    space = (' ' * indent); space ||= ''
    puts space + k.to_s
    indent += 2; tree_printer.call t[k]; indent -= 2
  end
end
tree_printer.call tree
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

Results also entered into cheat; sudo gem install cheat --source require.errtheblog.com; cheat exceptions for future reference.

Posted in  | Tags  | 3 comments | no trackbacks

Comments

  1. Avatar Eric Hodel said 4 days later:

    Its in the Ruby Quickref under Exceptions, Catch and Throw.

    PS: You forgot Errno::*

  2. Avatar Nick said 4 days later:

    Thanks for the link. Yes, I did omit Errno::* for brevity’s sake.

  3. Avatar g said 44 days later:

    this will give best of both worlds :)

    unless ARGV[0] #option to output errors

    next if cls.superclass == SystemCallError # avoid dumping Errno’s

    end

Trackbacks

Use the following link to trackback from your own site:
http://blog.nicksieger.com/articles/trackback/51