Try, Catch and Finally in C#: Exception Handling Done Right

A try block contains code that might throw an exception. A catch block handles a specific type of exception. A finally block runs afterwards in every case, whether the try block finished normally, returned early or threw.

try
{
    // Code that might throw
}
catch (FileNotFoundException ex)
{
    // Handle one specific failure, using ex.FileName or ex.Message
}
finally
{
    // Cleanup that must always happen
}

You need at least one catch or a finally; both are optional on their own.

A complete example

Console.WriteLine(Divide(10, 2));
Console.WriteLine(Divide(10, 0));

static string Divide(int a, int b)
{
    try
    {
        return (a / b).ToString();
    }
    catch (DivideByZeroException)
    {
        return "cannot divide by zero";
    }
    finally
    {
        Console.WriteLine($"finally ran for {a}/{b}");
    }
}

Output:

finally ran for 10/2
5
finally ran for 10/0
cannot divide by zero

Look at the order. The return value is computed first, then finally runs, then the method actually returns and the caller prints the result. A finally block runs even after return, break or continue.

When you do not need the exception object, leave out the variable name, as in catch (DivideByZeroException). That avoids an “unused variable” warning.

Catch specific exceptions, most specific first

Catch the exceptions you can actually do something about, and let the rest go up to a caller that can:

static int ReadPort(string path)
{
    try
    {
        string text = File.ReadAllText(path);
        return int.Parse(text.Trim());
    }
    catch (FileNotFoundException)
    {
        return 8080; // no config file: use the default
    }
    catch (FormatException ex)
    {
        throw new InvalidOperationException($"{path} does not contain a valid port number.", ex);
    }
}

The runtime checks catch blocks from top to bottom and uses the first one whose type matches. A block for a base class therefore has to come after blocks for its derived classes; putting catch (Exception) first is a compile error (CS0160), because the later blocks could never run.

The second catch wraps the low-level error in one that explains the context. Passing the original as the innerException argument keeps its details and stack trace available for logging.

Do not use exceptions for expected situations. If invalid input is normal, int.TryParse is clearer and far cheaper than catching FormatException, and File.Exists does not replace the catch above, because the file can disappear between the check and the read.

Exception filters

A when clause adds a condition. If it is false, the catch block is skipped as though its type had not matched:

using System.Net;

try
{
    string body = await http.GetStringAsync(url);
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
    Console.WriteLine("Not found, skipping.");
}

Other status codes and network errors pass through to the caller untouched. Filters run before the stack unwinds, so a crash dump still shows where the exception was thrown. HttpRequestException.StatusCode exists since .NET 5.

Rethrow with throw;

If you catch an exception only to log it, rethrow it with a bare throw;:

catch (Exception ex)
{
    Console.Error.WriteLine($"Import failed: {ex.Message}");
    throw;
}

throw ex; also compiles, but it resets the stack trace to the current line, so you lose the information about where the error really happened. Code analysis flags it as CA2200.

Catching Exception and doing nothing is the worst option of all. The program carries on in an unknown state and nobody learns why. Catch everything only at the top level (a Main method, a background worker loop, ASP.NET Core’s exception handling middleware), log it there, and decide whether to continue.

finally and using

The classic use of finally is releasing a resource:

var stream = File.OpenRead("data.bin");
try
{
    // read from the stream
}
finally
{
    stream.Dispose();
}

For anything that implements IDisposable, the using statement generates exactly this pattern, so in practice you write using var stream = File.OpenRead("data.bin"); instead. Keep finally for cleanup that is not a Dispose call, such as restoring a console color, releasing a SemaphoreSlim or resetting a flag.

Avoid return and throwing inside finally. Returning from finally is not even allowed in C#, and an exception thrown there replaces the one that was already in flight, which then disappears.

When finally does not run

finally is guaranteed for normal control flow and for handled exceptions, but not for everything:

  • Environment.FailFast and killing the process skip it.
  • A StackOverflowException terminates the process immediately, with no catch or finally.
  • If an exception is never caught, whether finally blocks run before the process terminates is up to the runtime. Do not rely on it for unhandled exceptions.

For async code, nothing special is needed: an exception from an awaited task is rethrown at the await, and the surrounding try, catch and finally behave as in synchronous code.

Related examples

Leave a Comment