Custom Exceptions कैसे बनाएँ
एक custom exception एक alarm है जिसे आप अपनी तरह की problem के लिए खुद नाम देते हैं, एक broken oven के लिए एक special bell की तरह। यह errors को clearer बनाता है।
In this page:
Syntax
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
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. #}
आम गलतियां
StandardErrorकी बजायExceptionसे inherit करना, इसलिए एक plainrescueइसे catch नहीं करता।- एक custom error को बिना
Errorsuffix के नाम देना, जो इसका purpose hide करता है। raise InsufficientFundsErrorसे बिना message के raise करना, इसलिए message class name है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: