Samuel Williams Wednesday, 05 August 2009

It is important to understand the place of StandardError in the hierarchy of ruby exceptions:

class TestException1 < StandardError
end
 
class TestException2 < Exception
end
 
begin
  begin
    raise TestException1
  rescue
    puts $!.class.name
  end
 
  begin
    raise TestException2
  rescue
    puts $!.class.name
  end
rescue Exception
  puts "Unhandled Exception #{$!.class.name}"
end

The result of this code is:

TestException1
Unhandled Exception TestException2

This behavior is consistent with the way ruby exceptions are designed; Errors which you can generally deal with are subclassed from StandardError, while errors which indicate a failure in the semantic meaning of the code or its execution inherit directly from Exception

class Object
  def self.subclasses(direct = false)
		classes = []
		
		ObjectSpace.each_object(Class) do |c|
			next unless c.superclass == self
			classes << c
		end
		
		return classes
  end
end

puts "Direct descendants of Exception: \n\t" + Exception.subclasses.join("\n\t")
puts "Direct descendants of StandardError: \n\t" + StandardError.subclasses.join("\n\t")

This gives us a list of exception classes:

# Direct descendants of Exception: 
	NoMemoryError
	ScriptError
	StandardError
	SignalException
	fatal
	SystemExit
# Direct descendants of StandardError: 
	SystemStackError
	LocalJumpError
	IOError
	RegexpError
	ZeroDivisionError
	ThreadError
	SystemCallError
	SecurityError
	RuntimeError
	NameError
	RangeError
	IndexError
	ArgumentError
	TypeError

Generally, if you are making your own exception class for non-fatal execution errors, you should inherit from StandardError or one of its descendants.

Comments

I take it there’s a small mistake in the conclusion, shouldn’t you inherit from StandardError instead of SystemError? Cheers for the post!

@Sebastiaan, yes this might be a slight mistake :D I’ll fix it.

Leave a comment

Please note, comments must be formatted using Markdown. Links can be enclosed in angle brackets, e.g. <www.codeotaku.com>.