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

The throw Keyword

In this page:

  1. The throw Keyword

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

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);
        }
    }
}
🔒

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.