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

Custom Exceptions कैसे बनाएँ

एक custom exception एक alarm है जिसे आप अपनी तरह की problem के लिए खुद नाम देते हैं, एक broken oven के लिए एक special bell की तरह। यह 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

आप StandardError (या एक ज़्यादा specific existing exception) से inherit करके अपनी खुद की exception class define कर सकते हैं, calling code को आपके domain के लिए एक precise, meaningful error type catch करने देते हुए।

Custom exceptions आमतौर पर super के जरिए parent constructor को एक message forward करते हैं। domain-specific failures report करने वाली libraries के लिए, एक generic error raise करने की बजाय, यह standard practice है।

Note: Custom exceptions को broader Exception class की बजाय StandardError से inherit करें, ताकि ये default से एक plain rescue clause से catch हों।

उदाहरण: 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. #}
आम गलतियां
  1. StandardError की बजाय Exception से inherit करना, इसलिए एक plain rescue इसे catch नहीं करता।
  2. एक custom error को बिना Error suffix के नाम देना, जो इसका purpose hide करता है।
  3. raise InsufficientFundsError से बिना message के raise करना, इसलिए message 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.