puts ZeroDivisionError < StandardError puts StandardError < Exception puts Exception < Object
In Ruby, ZeroDivisionError is a subclass of StandardError, which is a subclass of Exception, and Exception inherits from Object. The < operator checks if the left class is a subclass of the right class.
begin raise IOError, 'file error' rescue StandardError puts 'rescued StandardError' rescue IOError puts 'rescued IOError' end
In Ruby, IOError inherits from StandardError. The first rescue clause that matches the exception type is executed. Since rescue StandardError comes before rescue IOError, it catches the IOError first.
begin 1 / 0 rescue => e puts e.class end
Dividing an integer by zero in Ruby raises a ZeroDivisionError. The rescue block captures the exception and prints its class.
class MyError < StandardError; end class MySubError < MyError; end puts MySubError < StandardError puts MyError < Exception puts MySubError < Exception
Both MyError and MySubError inherit from StandardError, which inherits from Exception. The < operator returns true if the left class is a subclass of the right class.
In Ruby, Exception is the root class for all exceptions. StandardError and other error classes inherit from Exception. Object is the root of all Ruby objects but not specifically exceptions.