This document contains examples of error handling in Ruby using exceptions, rescue blocks, and custom error classes. It demonstrates raising different types of errors, accessing error details, and ensuring code is run after exceptions.
5. class Book
attr_accessor :author, :page_count, :title
def initialize(args = {})
@author = args[:author]
self.page_count = args[:page_count]
@title = args[:title]
end
def page_count=(value)
min, max = 1, 1000
if value < min || value > max
raise RangeError, "Value of [#{value}] outside bounds of [#{min}] to
[#{max}]."
else
@page_count = value
end
end
end
9. begin
3 / 0
rescue ZeroDivisionError => e
puts "#{e.class}: #{e.message}"
end
begin
"my string".odd?
rescue NoMethodError => e
puts "#{e.class}: #{e.message}"
end
10. class MyError < StandardError
attr_reader :thing
def initialize(msg="My default message", thing="apple")
@thing = thing
super(msg)
end
end
begin
raise MyError.new("my message", "my thing")
rescue => e
puts e.thing # "my thing"
end