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.
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"
endAttaching 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.
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
endA 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(orsuper(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 SpecificErrorself-documenting compared to inspecting generic RuntimeError messages. - Overriding initialize with keyword arguments changes what
raiseand.newcalls must look like for that class.
Practice what you learned
1. What class should a typical application-specific custom exception inherit from?
2. Why should a custom exception's initialize method call `super`?
3. What is the main benefit of adding attr_reader attributes to a custom exception class?
4. What is a common pattern for organizing multiple related custom exceptions in a gem or module?
5. If a custom exception's initialize is overridden to require keyword arguments like `attempted_amount:` and `available_balance:`, what happens if you call `raise MyError, "just a string"`?
Was this page helpful?
You May Also Like
Exception Handling in Ruby
Understand Ruby's begin/rescue/ensure/raise vocabulary for handling errors gracefully, including exception hierarchies, retry, and best practices for robust code.
Inheritance in Ruby
See how Ruby classes extend one another with single inheritance, how `super` calls parent implementations, and how method resolution order determines which method runs.
attr_accessor and Instance Variables
Learn how instance variables hold per-object state in Ruby, and how attr_accessor, attr_reader, and attr_writer generate boilerplate getter and setter methods.
Common Ruby Pitfalls
A tour of frequent Ruby mistakes — mutable defaults, frozen string surprises, nil handling, and block/proc return semantics — with fixes for each.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics