100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Ruby

Custom Exceptions in Ruby

Learn to design your own exception classes by subclassing StandardError, giving callers precise, catchable error types instead of generic RuntimeErrors or string messages.

Error Handling & MetaprogrammingIntermediate8 min readJul 9, 2026
Analogies

Custom Exceptions in Ruby

Ruby's built-in exceptions (ArgumentError, TypeError, RuntimeError) cover generic situations, but real applications have domain-specific failure modes: an insufficient account balance, an invalid state transition, a rate limit being exceeded. Defining custom exception classes lets calling code rescue exactly the failure it cares about, attach structured data to the error (not just a string message), and build a clear hierarchy that mirrors your application's own error taxonomy. This is far more maintainable than raising RuntimeError everywhere and inspecting message strings to figure out what actually went wrong.

🏏

Cricket analogy: Calling every dismissal just OUT without specifying bowled, caught, or run-out is like raising RuntimeError everywhere; a scorecard that distinguishes InsufficientRunsError from NoBallError lets commentators react to exactly what happened.

Defining a basic custom exception

A custom exception is just a class that inherits from StandardError (or one of its descendants, or occasionally a more specific built-in like ArgumentError if you're specializing it). Because Exception already implements #message and #initialize, the simplest custom exceptions require no code at all beyond the class declaration — but you'll usually want to add fields for structured context.

🏏

Cricket analogy: Registering a new dismissal type by simply subclassing the existing Out ruling requires no extra paperwork for a bare case, though most boards add extra fields like ball number for context, mirroring StandardError inheritance.

ruby
class InsufficientFundsError < StandardError
  def initialize(msg = "Account does not have enough funds for this transaction")
    super
  end
end

class Account
  attr_reader :balance

  def initialize(balance)
    @balance = balance
  end

  def withdraw(amount)
    raise InsufficientFundsError if amount > balance

    @balance -= amount
  end
end

account = Account.new(50)
begin
  account.withdraw(100)
rescue InsufficientFundsError => e
  puts e.message  #=> "Account does not have enough funds for this transaction"
end

Attaching structured data to exceptions

The real advantage of custom exception classes over plain strings is the ability to carry structured data — the attempted amount, the current balance, a request ID — that rescuing code can inspect programmatically rather than parsing out of a message string. Add extra attr_readers and accept extra arguments in initialize, always calling super with the final message so Exception's own bookkeeping still works.

🏏

Cricket analogy: A dismissal record that carries structured fields, ball number, bowler, fielder, rather than just the word out lets a review panel inspect exactly what happened, the way a custom exception carries attempted amount and balance instead of a plain message.

ruby
class InsufficientFundsError < StandardError
  attr_reader :attempted_amount, :available_balance

  def initialize(attempted_amount:, available_balance:)
    @attempted_amount = attempted_amount
    @available_balance = available_balance
    super("Tried to withdraw #{attempted_amount}, but only #{available_balance} is available")
  end
end

begin
  raise InsufficientFundsError.new(attempted_amount: 100, available_balance: 50)
rescue InsufficientFundsError => e
  puts e.message
  puts "Shortfall: #{e.attempted_amount - e.available_balance}"  #=> 50
end

A common pattern in gems and larger applications is a shared base error class per namespace, e.g. class PaymentError < StandardError; end, with specific errors like DeclinedError and InsufficientFundsError inheriting from it. Callers can then rescue the broad PaymentError to catch anything payment-related, or a specific subclass to handle one case precisely.

If you override initialize to accept custom keyword arguments (as above), you can no longer construct the exception with just a plain string via raise InsufficientFundsError, "some message" unless you also support that call signature — Ruby's raise passes its second argument to .new, so the signatures must be compatible.

  • Custom exceptions are classes that inherit from StandardError (directly or through a shared base error class).
  • Always call super (or super(message)) in a custom exception's initialize so Exception's built-in message handling still works.
  • Attach structured attributes with attr_reader so rescuing code can inspect data programmatically, not just parse strings.
  • A shared base error class per domain (e.g. PaymentError) lets callers rescue broadly or narrowly as needed.
  • Custom exception classes make rescue SpecificError self-documenting compared to inspecting generic RuntimeError messages.
  • Overriding initialize with keyword arguments changes what raise and .new calls must look like for that class.

Practice what you learned

Was this page helpful?

Topics covered

#Ruby#RubyStudyNotes#Programming#CustomExceptionsInRuby#Custom#Exceptions#Defining#Exception#ErrorHandling#StudyNotes#SkillVeris