← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 5 of 6

Custom Exceptions

In this page:

  1. Custom Exceptions

Custom Exceptions

You can define your own exception class by inheriting from StandardError (or a more specific existing exception), letting calling code catch a precise, meaningful error type for your domain. Custom exceptions usually forward a message to the parent constructor via super. This is standard practice for libraries reporting domain-specific failures, rather than raising a generic error.

Note: Inherit custom exceptions from StandardError, not the broader Exception class, so they're caught by a plain rescue clause by default.

Example: Custom Exceptions

markup
class InsufficientFundsError < StandardError; end

class Account
  attr_reader :balance

  def initialize(balance)
    @balance = balance
  end

  def withdraw(amount)
    raise InsufficientFundsError, "Not enough funds" if amount > @balance
    @balance -= amount
  end
end

account = Account.new(100)

begin
  account.withdraw(500)
rescue InsufficientFundsError => e
  puts e.message
end
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.