Custom Exceptions बनाना
एक custom exception एक alarm है जिसे आप अपनी खुद की खास तरह की समस्या के लिए खुद design करते हैं। यह error messages को आपके program के लिए मायने रखने वाला बनाता है।
In this page:
Syntax
class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}
throw new CustomException("message");
Custom Exceptions
आप Exception (या एक ज़्यादा specific subclass) से inherit करके अपनी खुद की exception type define कर सकते हैं, जो calling code को आपके domain के लिए एक सटीक, मायने रखने वाला error type catch करने देता है।
Custom exceptions आमतौर पर एक message base constructor को forward करते हैं। यह domain-specific failures report करने वाली libraries के लिए standard practice है।
Note:
Custom exceptions को "Exception" पर खत्म होने वाले नाम दें, जैसे
InsufficientFundsException।उदाहरण: Custom Exceptions
using System;
class InsufficientFundsException : Exception
{
public InsufficientFundsException(string message) : base(message) { }
}
class Account
{
public decimal Balance = 100;
public void Withdraw(decimal amount)
{
if (amount > Balance)
throw new InsufficientFundsException("Not enough funds");
Balance -= amount;
}
}
class Program
{
static void Main(string[] args)
{
Account acc = new Account();
try
{
acc.Withdraw(500);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine(ex.Message);
}
}
}
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. #}
आम गलतियां
- class name को
Exceptionपर खत्म न करना, जो .NET naming convention तोड़ता है। - base constructor को message के साथ call करना भूल जाना, जिससे message खो जाता है।
Exceptionके बजायApplicationExceptionसे derive करना, जिसकी सिफारिश नहीं की जाती।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: