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

amount
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
  1. amount ← 10, balance ← 20

    10amount→ 10 = 10  #@amount=5, 3011balance→ 20 = 201213begin14  remaining = withdraw(balance20, amount10)15  puts "remaining=#{remaining}"
  2. def withdraw(balance, amount)

    4def withdraw(balance20, amount10)5  raise BalanceErrorBalanceError, "not enough balance" if amount10 > balance2067  balance20 - amount108end
  3. remaining ← 10

    13begin14  remaining→ 10 = withdraw(balance20, amount10)15  puts "remaining=#{remaining10}"16rescue BalanceError => error
    outputremaining=10
  1. amount ← 5, balance ← 20

    10amount→ 5 = 511balance→ 20 = 201213begin14  remaining = withdraw(balance20, amount5)15  puts "remaining=#{remaining}"
  2. def withdraw(balance, amount)

    4def withdraw(balance20, amount5)5  raise BalanceErrorBalanceError, "not enough balance" if amount5 > balance2067  balance20 - amount58end
  3. remaining ← 15

    13begin14  remaining→ 15 = withdraw(balance20, amount5)15  puts "remaining=#{remaining15}"16rescue BalanceError => error
    outputremaining=15
  1. amount ← 30, balance ← 20

    10amount→ 30 = 3011balance→ 20 = 201213begin14  remaining = withdraw(balance20, amount30)15  puts "remaining=#{remaining}"
  2. def withdraw(balance, amount)

    4def withdraw(balance20, amount30)5  raise BalanceErrorBalanceError, "not enough balance" if amount30 > balance2067  balance20 - amount308end
  3. puts "error=#{error.message}"

    16rescue BalanceError => error17  puts "error=#{error.messagenot enough balance}"18end
    outputerror=not enough balance