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

throw Keyword क्या है

throw keyword जान-बूझकर alarm बजाता है, जैसे चिल्लाना 'रुको, कुछ गलत है!'। आप इसका उपयोग तब करते हैं जब आपका code कोई समस्या देखता है और आगे नहीं बढ़ सकता।

In this page:

  1. The throw Keyword
Syntax
csharp
throw new ExceptionType("message");

catch (ExceptionType ex)
{
    throw;   // rethrow, keeps the original stack trace
}

The throw Keyword

throw explicitly एक exception उठाता है, या तो एक नया या एक पहले से पकड़ा गया exception फिर से throw करते हुए।

किसी catch block के अंदर साधारण throw; से फिर से throw करना original stack trace को संरक्षित रखता है, जबकि throw ex; इसे reset कर देता है। invalid input या state पकड़ने वाले methods आमतौर पर एक error code return करने के बजाय throw करते हैं।

Warning: फिर से throw करते समय throw ex; के बजाय throw; को प्राथमिकता दें, ताकि debugging tools दिखा सकें कि error असल में कहां उत्पन्न हुआ।

उदाहरण: The throw Keyword

markup
using System;

class Program
{
    static void CheckAge(int age)
    {
        if (age < 0)
            throw new ArgumentException("Age cannot be negative");
        Console.WriteLine($"Age {age} is valid");
    }

    static void Main(string[] args)
    {
        try
        {
            CheckAge(-5);
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine("Error: " + 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. किसी catch block में throw ex; लिखना, जो stack trace reset कर देता है; फिर से throw करने के लिए throw; का उपयोग करें।
  2. किसी string या दूसरे non-exception object को throw करना, जिसकी अनुमति नहीं है।
  3. normal control flow के लिए एक exception फेंकना, जो धीमा और भ्रामक है।
🔒

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.