Exceptions and Safety
Custom Exception
A custom exception class gives a specific name to one kind of failure.
custom exception
A custom exception class can inherit from `StandardError` and be rescued by name.
Custom Exception
custom_exception.rb
Replay: real traced execution (multi-file project)
class BalanceError < StandardError
end
def withdraw(balance, amount)
raise BalanceError, "not enough balance" if amount > balance
balance - amount
end
amount = 10
balance = 20
begin
remaining = withdraw(balance, amount)
puts "remaining=#{remaining}"
rescue BalanceError => error
puts "error=#{error.message}"
end
class BalanceError < StandardError
end
def withdraw(balance, amount)
raise BalanceError, "not enough balance" if amount > balance
balance - amount
end
amount = 5
balance = 20
begin
remaining = withdraw(balance, amount)
puts "remaining=#{remaining}"
rescue BalanceError => error
puts "error=#{error.message}"
end
class BalanceError < StandardError
end
def withdraw(balance, amount)
raise BalanceError, "not enough balance" if amount > balance
balance - amount
end
amount = 30
balance = 20
begin
remaining = withdraw(balance, amount)
puts "remaining=#{remaining}"
rescue BalanceError => error
puts "error=#{error.message}"
end
amount ← 10, balance ← 20
10amount→ 10 = 10 #@amount=5, 3011balance→ 20 = 201213begin14 remaining = withdraw(balance20, amount10)15 puts "remaining=#{remaining}"def withdraw(balance, amount)
4def withdraw(balance20, amount10)5 raise BalanceErrorBalanceError, "not enough balance" if amount10 > balance2067 balance20 - amount108endremaining ← 10
13begin14 remaining→ 10 = withdraw(balance20, amount10)15 puts "remaining=#{remaining10}"16rescue BalanceError => erroroutputremaining=10
amount ← 5, balance ← 20
10amount→ 5 = 511balance→ 20 = 201213begin14 remaining = withdraw(balance20, amount5)15 puts "remaining=#{remaining}"def withdraw(balance, amount)
4def withdraw(balance20, amount5)5 raise BalanceErrorBalanceError, "not enough balance" if amount5 > balance2067 balance20 - amount58endremaining ← 15
13begin14 remaining→ 15 = withdraw(balance20, amount5)15 puts "remaining=#{remaining15}"16rescue BalanceError => erroroutputremaining=15
amount ← 30, balance ← 20
10amount→ 30 = 3011balance→ 20 = 201213begin14 remaining = withdraw(balance20, amount30)15 puts "remaining=#{remaining}"def withdraw(balance, amount)
4def withdraw(balance20, amount30)5 raise BalanceErrorBalanceError, "not enough balance" if amount30 > balance2067 balance20 - amount308endputs "error=#{error.message}"
16rescue BalanceError => error17 puts "error=#{error.messagenot enough balance}"18endoutputerror=not enough balance