Exceptions ใน Ruby แค่ classes Exception hierarchy ประกอบด้วย classes ทั้งหมดที่ inherit จาก Exception
นี่คือ exception hierarchy สำหรับ 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
Practical Uses
เหตุผลที่ exceptions จัดเป็น class tree คือให้ rescue similar types of exception ได้ง่าย
เช่น code:
begin do_something rescue StandardError => e end
จะ rescue ไม่ใช่แค่ StandardError แต่ทุก exception ที่ inherit จากมัน ซึ่งเป็นเกือบ exception ทุกตัวที่คุณสนใจ
ในโค้ดของคุณ custom exceptions อาจ inherit จาก single base class:
module MyLib class Error < StandardError end class TimeoutError < Error end class ConnectionError < Error end end ... begin do_something rescue MyLib::Error => e # Rescues any of the exceptions defined above end