Exception trong Ruby chỉ là class. Hierarchy exception gồm tất cả class kế thừa từ `Exception`.
Dưới đây là exception hierarchy cho Ruby 2.1 standard library.
Exception
NoMemoryError
ScriptError
LoadError
NotImplementedError
SyntaxError
SecurityError
SignalException
Interrupt
StandardError -- default for rescue
ArgumentError
UncaughtThrowError
EncodingError
FiberError
IOError
EOFError
IndexError
KeyError
StopIteration
LocalJumpError
NameError
NoMethodError
RangeError
FloatDomainError
RegexpError
RuntimeError -- default for raise
SystemCallError
Errno::*
ThreadError
TypeError
ZeroDivisionError
SystemExit
SystemStackError
Ứng dụng thực tế
Lý do exception sắp xếp thành cây class: để bạn dễ dàng rescue nhóm exception tương tự.
Ví dụ code:
begin
do_something
rescue StandardError => e
end
Sẽ rescue không chỉ `StandardError`, mà cả exception kế thừa từ nó. Đó là hầu như mọi exception bạn quan tâm.
Trong code riêng, có thể để tất cả custom exception kế thừa từ một base class:
module MyLib
class Error < StandardError; end
class TimeoutError < Error; end
class ConnectionError < Error; end
end
begin
do_something
rescue MyLib::Error => e
# Rescue bất kỳ exception nào định nghĩa ở trên
end