8.9.5 The throw statement
throw statement throws an exception.
- throw expressionopt ;
throw statement with an expression throws the value produced by evaluating the expression. The expression must denote a value of the class type
System.Exception or of a class type that derives from
System.Exception. If evaluation of the expression produces
System.NullReferenceException is thrown instead.
throw statement with no expression can be used only in a
catch block, in which case that statement re-throws the exception that is currently being handled by that
throw statement unconditionally transfers control elsewhere, the end point of a
throw statement is never reachable.
When an exception is thrown, control is transferred to the first
catch clause in an enclosing
try statement that can handle the exception. The process that takes place from the point of the exception being thrown to the point of transferring control to a suitable exception handler is known as exception propagation. Propagation of an exception consists of repeatedly evaluating the following steps until a
catch clause that matches the exception is found. In this description, the throw point is initially the location at which the exception is thrown.
- In the current function member, each
trystatement that encloses the throw point is examined. For each statement
S, starting with the innermost
trystatement and ending with the outermost
trystatement, the following steps are evaluated:
- If the
Sencloses the throw point and if S has one or more
catchclauses are examined in order of appearance to locate a suitable handler for the exception. The first
catchclause that specifies the exception type or a base type of the exception type is considered a match. A general
catchclause (Section 8.10) is considered a match for any exception type. If a matching
catchclause is located, the exception propagation is completed by transferring control to the block of that
- Otherwise, if the
tryblock or a
Sencloses the throw point and if
finallyblock, control is transferred to the
finallyblock. If the
finallyblock throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the
finallyblock, processing of the current exception is continued.
- If an exception handler was not located in the current function member invocation, the function member invocation is terminated. The steps above are then repeated for the caller of the function member with a throw point corresponding to the statement from which the function member was invoked.
- If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.