The throw Keyword
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: