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

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:

  1. The throw Keyword
Syntax
csharp
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

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. #}
Common Mistakes
  1. Writing throw ex; in a catch block, which resets the stack trace; use throw; to rethrow.
  2. Throwing a string or other non-exception object, which is not allowed.
  3. 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:

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.