← Back to C# Course | Chapter 10: Exception Handling | Lesson 3 of 6

Custom Exceptions बनाना

एक custom exception एक alarm है जिसे आप अपनी खुद की खास तरह की समस्या के लिए खुद design करते हैं। यह error messages को आपके program के लिए मायने रखने वाला बनाता है।

In this page:

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

markup
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);
        }
    }
}
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. class name को Exception पर खत्म न करना, जो .NET naming convention तोड़ता है।
  2. base constructor को message के साथ call करना भूल जाना, जिससे message खो जाता है।
  3. Exception के बजाय ApplicationException से derive करना, जिसकी सिफारिश नहीं की जाती।
🔒

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.