throw Keyword क्या है
throw keyword जान-बूझकर alarm बजाता है, जैसे चिल्लाना 'रुको, कुछ गलत है!'। आप इसका उपयोग तब करते हैं जब आपका code कोई समस्या देखता है और आगे नहीं बढ़ सकता।
In this page:
Syntax
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
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);
}
}
}
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. #}
आम गलतियां
- किसी catch block में
throw ex;लिखना, जो stack trace reset कर देता है; फिर से throw करने के लिएthrow;का उपयोग करें। - किसी string या दूसरे non-exception object को throw करना, जिसकी अनुमति नहीं है।
- normal control flow के लिए एक exception फेंकना, जो धीमा और भ्रामक है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: