C# Reference ยท Keywords and Statements
The throw statement and expression
Reference for C# throw: raising exceptions, rethrowing with throw; versus throw ex;, throw expressions, argument-check helpers and inner exceptions.
throw raises an exception. Control leaves the current method immediately and the runtime searches up the call stack for a matching catch block, running finally blocks on the way. throw can be used as a statement and, since C# 7, as an expression in places such as ??, the conditional operator and expression-bodied members.
Inside a catch block a bare throw; rethrows the exception being handled without changing its stack trace. Everywhere else, throw needs an expression whose type is System.Exception or a subclass.
if (age < 0) { throw new ArgumentOutOfRangeException(nameof(age), "Age cannot be negative."); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
throw expression; // statement or expression form throw; // rethrow inside a catch block
| Name | Description |
|---|---|
expression |
An object of type Exception or a derived type. Throwing null raises NullReferenceException instead. |
Errors: throw; outside a catch block fails with CS0156. Throwing something that is not an Exception is CS0029. A throw expression is not allowed in every position (for example as an operand of == directly); it works as the right side of ??, in a conditional operator branch, in an expression-bodied member and in a lambda body.
Usage notes
throw;versusthrow e;.throw;keeps the original stack trace.throw e;resets it to the current line, hiding where the problem started. UseExceptionDispatchInfo.Capture(e).Throw()to rethrow later from another place without losing it.- Choose a precise type:
ArgumentNullException,ArgumentOutOfRangeException,InvalidOperationException(object state is wrong),NotSupportedException,NotImplementedException(placeholder). Create your own class when callers need to catch it separately. - Guard helpers:
ArgumentNullException.ThrowIfNull(x),ArgumentException.ThrowIfNullOrEmpty(s),ArgumentOutOfRangeException.ThrowIfNegative(n)capture the parameter name automatically and keep the method short. - Wrap with context: pass the caught exception as the second constructor argument so the chain is kept in
InnerException. - Do not throw from finalizers,
Dispose(when avoidable) or property getters in ordinary cases. - Cost: throwing and catching is far slower than returning a result, so use exceptions for exceptional conditions and
TryXxxmethods for expected failures. - Async code: in an
asyncmethod a thrown exception is stored in the returnedTaskand rethrown when awaited.