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

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:

  1. Custom Exceptions
Syntax
ruby
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

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
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
  1. Inheriting from Exception instead of StandardError, so a plain rescue does not catch it.
  2. Naming a custom error without the Error suffix, which hides its purpose.
  3. Raising with raise InsufficientFundsError and 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:

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.