C# Throw Statement

Throw keyword

Throw generates or translates exceptions. By using a throw statement inside a catch block, you can change the resulting exception. Alternatively you can throw a new exception nearly anywhere in C# code. The throw statement is versatile and essential for the alternate control structure of exception handling.

Keywords

This C# example reveals the use of the throw keyword. Throw is a way to manually cause an error.

Examples

Note

To begin, let's look at three methods A, B, and C that use the throw statement in different ways. Method A uses a throw statement with no argument. This can be thought of as a rethrow—it simply throws the same exception already being handled.

Continuing on, method B throws a named exception variable. This too is a rethrow construct, but you can collect information about the exception beforehand if needed. Method C generates a new exception with the throw statement. You can use a throw statement in this way to add custom error conditions.

Program that uses throw statements [C#]

using System;

class Program
{
    static void Main()
    {
	// Comment out the first 1-2 method invocations.
	try
	{
	    A();
	    B();
	    C(null);
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex);
	}
    }

    static void A()
    {
	// Rethrow syntax.
	try
	{
	    int value = 1 / int.Parse("0");
	}
	catch
	{
	    throw;
	}
    }

    static void B()
    {
	// Filtering exception types.
	try
	{
	    int value = 1 / int.Parse("0");
	}
	catch (DivideByZeroException ex)
	{
	    throw ex;
	}
    }

    static void C(string value)
    {
	// Generate new exception.
	if (value == null)
	{
	    throw new ArgumentNullException("value");
	}
    }
}

Possible program output
    These three exceptions are thrown.

System.DivideByZeroException: Attempted to divide by zero.
System.DivideByZeroException: Attempted to divide by zero.
System.ArgumentNullException: Value cannot be null.
Parameter name: value
Catch DivideByZeroException ArgumentException

Summary

The C# programming language

The exception handling mechanism in the C# language reveals an alternative control pathway, one that separates error-specific logic from regular processing. The throw statement, then, provides an essential ability to rethrow an exception or generate a new exception. Throwing, then, switches the program execution into the alternative exception handling pathways.

Exception Handling
.NET