Custom Exceptions
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: