Ruby StandardError & Exception
Author: Samuel Williams When: Wednesday, 05 August 2009It 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 SystemError or one of its descendants.
Comments
Please note, you can leave a comment that uses (limited) XHTML and Textile syntax.