Partilhar via


throw (C# Reference)

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

Remarks

The thrown exception is an object whose class is derived from System.Exception, as shown in the following example.

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

Usually the throw statement is used with try-catch or try-finally statements. A throw statement can be used in a catch block to re-throw the exception that the catch block caught. In this case, the throw statement does not take an exception operand. For more information and examples, see try-catch (C# Reference) and How to: Explicitly Throw Exceptions.

Example

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.
    */

Code Example

See the examples in try-catch (C# Reference) and How to: Explicitly Throw Exceptions.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Tasks

How to: Explicitly Throw Exceptions

Reference

try-catch (C# Reference)

The try, catch, and throw Statements in C++

C# Keywords

Exception Handling Statements (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference