Custom Exceptions
A custom exception is an alarm you name yourself for your own kind of problem, like a special bell for a broken oven. It makes errors clearer.
In this page:
Syntax
class CustomError < StandardError
def initialize(msg = "default message")
super
end
end
raise CustomError
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Inheriting from
Exceptioninstead ofStandardError, so a plainrescuedoes not catch it. - Naming a custom error without the
Errorsuffix, which hides its purpose. - Raising with
raise InsufficientFundsErrorand no message, so the message is the class name.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: