The throw Keyword
The throw keyword sounds the alarm on purpose, like shouting 'stop, something is wrong!'. You use it when your code spots a problem and cannot go on.
In this page:
Syntax
throw new ExceptionType("message");
catch (ExceptionType ex)
{
throw; // rethrow, keeps the original stack trace
}
The throw Keyword
throw raises an exception explicitly, either a new one or an existing caught exception being rethrown.
Rethrowing with plain throw; inside a catch block preserves the original stack trace, while throw ex; resets it. Methods that detect invalid input or state typically throw rather than return an error code.
Warning:
Prefer
throw; over throw ex; when rethrowing, so debugging tools show where the error actually originated.Example: 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. #}
Common Mistakes
- Writing
throw ex;in a catch block, which resets the stack trace; usethrow;to rethrow. - Throwing a string or other non-exception object, which is not allowed.
- Throwing an exception for normal control flow, which is slow and confusing.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: