Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
C# Reference
C# Keywords
Statement Types
 throw

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
C# Language Reference
throw (C# Reference)

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. When an exception is thrown, the program looks for the catch statement that handles this exception.

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.

// throw example
using System;
public class ThrowTest 
{
    static void Main() 
    {
        string s = null;

        if (s == null) 
        {
            throw new ArgumentNullException();
        }

        Console.Write("The string s is null"); // not executed
    }
}

The ArgumentNullException exception occurs.

See the try-catch, try-finally, and try-catch-finally examples.

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

  • 5.3.3.11 Throw statements

  • 8.9.5 The throw statement

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker