| title | throw (C# Reference) | |||
|---|---|---|---|---|
| ms.date | 03/02/2015 | |||
| ms.prod | .net | |||
| ms.technology |
|
|||
| ms.topic | article | |||
| f1_keywords |
|
|||
| helpviewer_keywords |
|
|||
| ms.assetid | 5ac4feef-4b1a-4c61-aeb4-61d549e5dd42 | |||
| caps.latest.revision | 22 | |||
| author | rpetrusha | |||
| ms.author | ronpet |
Signals the occurrence of an exception during program execution.
The syntax of throw is:
throw [e]where e is an instance of a class derived from xref:System.Exception?displayProperty=nameWithType. The following example uses the throw statement to throw an xref:System.IndexOutOfRangeException if the argument passed to a method named GetNumber does not correspond to a valid index of an internal array.
[!code-csharpcsrefKeyword#1]
Method callers then use a try-catch or try-catch-finally block to handle the thrown exception. The following example handles the exception thrown by the GetNumber method.
[!code-csharpcsrefKeyword#2]
throw can also be used in a catch block to re-throw an exception handled in a catch block. In this case, throw does not take an exception operand. It is most useful when a method passes on an argument from a caller to some other library method, and the library method throws an exception that must be passed on to the caller. For example, the following example re-throws an xref:System.NullReferenceException that is thrown when attempting to retrieve the first character of an uninitialized string.
[!code-csharpcsrefKeyword#3]
Important
You can also use the throw e syntax in a catch block to instantiate a new exception that you pass on to the caller. In this case, the stack trace of the original exception, which is available from the xref:System.Exception.StackTrace property, is not preserved.
Starting with C# 7, throw can be used as an expression as well as a statement. This allows an exception to be thrown in contexts that were previously unsupported. These include:
-
the conditional operator. The following example uses a
throwexpression to throw an xref:System.ArgumentException if a method is passed an empty string array. Before C# 7, this logic would need to appear in anif/elsestatement.[!code-csharpcsrefKeyword#4]
-
the null-coalescing operator. In the following example, a
throwexpression is used with a null-coalescing operator to throw an exception if the string assigned to aNameproperty isnull.[!code-csharpcsrefKeyword#5]
-
an expression-bodied lambda or method. The following example illustrates an expression-bodied method that throws an xref:System.InvalidCastException because a conversion to a xref:System.DateTime value is not supported.
[!code-csharpcsrefKeyword#6]
[!INCLUDECSharplangspec]
C# Reference
C# Programming Guide
try-catch
The try, catch, and throw Statements in C++
C# Keywords
Exception Handling Statements
How to: Explicitly Throw Exceptions