C# Reference ยท Keywords and Statements
The try, catch and finally statements
Reference for C# try, catch and finally: catching specific exceptions, exception filters with when, cleanup in finally, rethrowing and the order of catch clauses.
A try statement protects a block of code. If an exception is thrown inside the try block, the runtime looks at the catch clauses from top to bottom and runs the first one whose type matches (and whose optional when filter is true). A finally block runs afterwards in every case: normal completion, a caught exception, an uncaught exception or a jump such as return.
You may combine try with one or more catch clauses, with finally, or with both. Catch the most specific exceptions you can actually handle, and let everything else propagate.
try { int n = int.Parse(text); } catch (FormatException e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("always runs"); }
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
try { ... } catch (ExceptionType name) when (condition) { ... } catch (ExceptionType) { ... } catch { ... } finally { ... }
| Name | Description |
|---|---|
ExceptionType |
A class derived from System.Exception. Matches that type and all its subclasses. |
name |
Optional variable holding the exception inside the block. |
when (condition) |
Optional filter; the clause is skipped (without unwinding) when it is false. |
Errors: a catch for a base class placed before a catch for a derived class gives CS0160 because the later clause could never run. A try with neither catch nor finally is a syntax error. Catching a type that is not an Exception is CS0155, and try with nothing after it gives CS1524.
Usage notes
- Order: put the most specific
catchfirst and the general one last. throw;versusthrow e;. A barethrow;rethrows and preserves the stack trace;throw e;resets it. Preferthrow;.- Exception filters run before the stack unwinds, so a debugger or a log still sees the original state. Use them for conditions instead of catching and rethrowing.
- Do not swallow errors. An empty
catch { }hides bugs. CatchExceptiononly at the top of a program or request, to log and report. finallyruns even onreturn,breakandcontinue, but not if the process is torn down byEnvironment.FailFast, a stack overflow or a power loss. You cannot jump out of afinallyblock with a jump statement.- Cleanup of disposable objects is shorter with
usingthan withtry/finally. - Cost: a
tryblock is almost free when nothing is thrown; throwing is slow (microseconds), so do not use exceptions for ordinary control flow. PreferTryParsepatterns. - Uncatchable cases:
StackOverflowExceptionand out-of-memory corruption cannot be reliably handled. In async methods, exceptions are stored in the returnedTaskand surface when youawaitit.