Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

throw (C# Reference)

Updated: September 2008

The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.

The thrown exception is an object whose class is derived from System.Exception, for example:

class MyException : System.Exception {}
// ...
throw new MyException();

Usually the throw statement is used with try-catch or try-finally statements.

You can also rethrow a caught exception using the throw statement. For more information and examples, see try-catch and Throwing Exceptions.

This example demonstrates how to throw an exception using the throw statement.

public class ThrowTest2
{

    static int GetNumber(int index)
    {
        int[] nums = { 300, 600, 900 };
        if (index > nums.Length)
        {
            throw new IndexOutOfRangeException();
        }
        return nums[index];

    }
    static void Main() 
    {
        int result = GetNumber(3);

    }
}
/*
    Output:
    The System.IndexOutOfRangeException exception occurs.
*/

For more information, see the following sections in the C# Language Specification:

  • 5.3.3.11 Throw statements

  • 8.9.5 The throw statement

Date

History

Reason

September 2008

Fixed example code.

Customer feedback.

Community Additions

ADD
Show:
© 2015 Microsoft