Skip to content
Tutorials Center
My learning

Topics

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.

C#
try
{
    int n = int.Parse(text);
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
finally
{
    Console.WriteLine("always runs");
}

Try it

C# Specific catches and finally

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.

C# Filters, rethrow and finally order

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

C#
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 catch first and the general one last.
  • throw; versus throw e;. A bare throw; rethrows and preserves the stack trace; throw e; resets it. Prefer throw;.
  • 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. Catch Exception only at the top of a program or request, to log and report.
  • finally runs even on return, break and continue, but not if the process is torn down by Environment.FailFast, a stack overflow or a power loss. You cannot jump out of a finally block with a jump statement.
  • Cleanup of disposable objects is shorter with using than with try/finally.
  • Cost: a try block is almost free when nothing is thrown; throwing is slow (microseconds), so do not use exceptions for ordinary control flow. Prefer TryParse patterns.
  • Uncatchable cases: StackOverflowException and out-of-memory corruption cannot be reliably handled. In async methods, exceptions are stored in the returned Task and surface when you await it.