skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

C# try/catch: Exception Handling in C# with Examples

How to handle exceptions in C# with try/catch/finally, throw, custom exceptions, and when filters, with copy-paste examples tested on .NET 10.

7 min read
A taut black safety net, standing in for the way try/catch catches exceptions before they crash your program. Photo by Andrés Canchón on Unsplash.

Quick answer

Wrap code that can fail in a try block, handle the failure in one or more catch blocks ordered most-specific first, and put cleanup that must always run in a finally block. The three keywords are try, catch, and finally.

Software can do many tasks such as read files, perform HTTP calls, and parsing input; all actions that throw exceptions, and the worst unhandled exceptions crash your program. C#’s try/catch gives you the opportunity to recover or report the failure instead.

In this post, we’ll cover try/catch/finally, throwing exceptions, exception filters, and custom exception types, with examples you can paste into a project.

Every snippet here targets current .NET (.NET 10 / C# 14).

What is try/catch in C#?

You put code that might fail inside a try block. If it throws, execution jumps to a matching catch block, where you decide what to do. A finally block always executes the code block afterward either way.

try
{
var text = File.ReadAllText("config.json");
Console.WriteLine(text);
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Missing file: {ex.FileName}");
}
finally
{
Console.WriteLine("Done.");
}

In this example, without the try/catch, a missing file throws a FileNotFoundException that unwinds the call stack and terminates the program. With it, you catch the failure and keep running.

Anatomy of an exception

Every exception in .NET derives from System.Exception, so whatever type you catch, a common set of members is always available on ex. These are the ones you’ll read most often.

Member Type What it holds
Message string A human-readable description of what went wrong.
StackTrace string The call stack at the point the exception was thrown.
InnerException Exception? The exception that caused this one, when it was wrapped. null if there isn’t one.
Data IDictionary A bag of key/value pairs you can attach for extra context.
Source string? The name of the app or object that caused the error.
TargetSite MethodBase? The method that threw.
HResult int The numeric error code, useful when interoping with native or COM errors.
HelpLink string? A link to help text, if the thrower set one.

Derived types add their own properties on top. FileNotFoundException carries a FileName, ArgumentException carries a ParamName, and an HttpRequestException carries a StatusCode. That’s why catching the specific type is worth it: you get data the base class doesn’t expose.

catch (Exception ex)
{
Console.WriteLine(ex.Message); // what went wrong
Console.WriteLine(ex.StackTrace); // where it happened
Console.WriteLine(ex.InnerException?.Message); // the wrapped cause, if any
ex.Data["OrderId"] = 42; // attach context before rethrowing
throw;
}

Call ex.ToString() to get the type name, message, and stack trace in one string, which is what logging frameworks record and what you see printed when an exception goes unhandled. When exceptions are nested, GetBaseException() walks the InnerException chain and returns the original cause.

Catching specific exceptions (order matters)

A single try can have several catch blocks. C# uses the first one whose type matches the thrown exception, so order them most-specific first.

try
{
var json = File.ReadAllText("config.json");
var config = JsonSerializer.Deserialize<Config>(json);
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"No config at {ex.FileName}, using defaults.");
}
catch (JsonException ex)
{
Console.WriteLine($"Config is not valid JSON: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected failure: {ex.Message}");
throw;
}

Put the general catch (Exception) last. A broad catch before a more specific one is unreachable, and the compiler rejects it with an error. Catch Exception only when you plan to log and rethrow, or when the method handles every failure the same way.

finally: cleanup that always runs

A finally block runs whether the try succeeded, threw, or returned early. Use it for cleanup you don’t want to skip, like releasing a handle, resetting state, or logging a message.

var connection = OpenConnection();
try
{
connection.Run(query);
}
finally
{
connection.Close(); // runs even if Run throws
}

For anything that implements IDisposable, prefer using over a hand-written finally. It calls Dispose for you at the end of the scope.

using var connection = OpenConnection();
connection.Run(query); // Dispose() runs automatically

Throwing exceptions with throw

Use throw to raise an exception when your method can’t do what the caller asked. Pick the built-in type that fits, and pass the parameter name when the problem is a bad argument.

public decimal Withdraw(decimal amount)
{
if (amount <= 0)
throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive.");
if (amount > Balance)
throw new InvalidOperationException("Insufficient funds.");
Balance -= amount;
return Balance;
}

throw vs throw ex

When you catch an exception and want to rethrow it, use bare throw;. It preserves the original stack trace, so you can still see where the exception started.

catch (Exception ex)
{
Log(ex);
throw; // keeps the original stack trace
}

Writing throw ex; instead resets the stack trace to this line, which hides where the problem came from. Reach for bare throw; unless you have a specific reason not to. If you need to capture an exception and rethrow it later from somewhere else, see ExceptionDispatchInfo and capturing exceptions.

Guard clauses with throw helpers

Modern .NET ships static helpers that throw for you, which cuts the boilerplate of a hand-written if and throw.

public void Register(string name, Order order)
{
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentNullException.ThrowIfNull(order);
// name and order are guaranteed non-null past this point
}

These read better than the equivalent if (name is null) throw new ArgumentNullException(...) and set the parameter name for you.

Exception filters with when

A when clause adds a condition to a catch. The block runs only if the filter is true; otherwise the exception keeps unwinding as if that catch weren’t there.

try
{
await SendRequest();
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests)
{
await Task.Delay(RetryDelay);
await SendRequest();
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.StatusCode}");
}

The filter runs without unwinding the stack, so you keep more diagnostic context than you would by catching, checking, and rethrowing. It’s handy for retrying on one status code while letting the rest fall through.

Custom exceptions

Create your own exception type when callers need to catch your failure distinctly from everything else. Derive from Exception, keep the Exception suffix in the name, and provide a constructor that accepts an inner exception.

public class OrderNotFoundException : Exception
{
public OrderNotFoundException(int orderId)
: base($"Order {orderId} was not found.")
{
OrderId = orderId;
}
public OrderNotFoundException(int orderId, Exception inner)
: base($"Order {orderId} was not found.", inner)
{
OrderId = orderId;
}
public int OrderId { get; }
}

The extra OrderId property gives the handler structured data instead of a parsed message. Don’t add a custom type when a built-in one like ArgumentException or InvalidOperationException already says what went wrong.

Best practices for exception handling

A few rules keep exception handling useful instead of noisy.

  • Don’t use exceptions for control flow. When a failure is expected, use a Try* method. int.TryParse(input, out var number) returns false on bad input instead of throwing, which is cheaper and clearer. See convert a string to an int in C# for the pattern.
  • Catch only what you can handle. If a method can’t do anything useful with an exception, let it bubble up to code that can.
  • Never swallow silently. An empty catch { } hides bugs. Log it, handle it, or rethrow.
  • Keep try blocks small. Wrap the line that can fail, not the whole method, so the catch targets the real source.

Exceptions also cost more than a normal return: they allocate, walk the stack, and add garbage-collection pressure. That’s a reason to avoid throwing on a hot path, not a reason to avoid exceptions for the error cases they’re built for.

Frequently Asked Questions

What is the difference between throw and throw ex in C#?

Bare throw; rethrows the current exception and preserves its original stack trace. throw ex; resets the stack trace to the line where you wrote it, hiding where the exception started. Prefer throw;.

Should I catch Exception in C#?

Catch Exception only when you log and rethrow, or when a top-level handler treats every failure the same way. For normal code, catch the specific types you know how to handle and let the rest bubble up.

What is the difference between try/catch and try/finally?

catch handles an exception that was thrown. finally runs cleanup whether or not an exception occurred, and doesn’t handle anything. You can use both together, or try/finally on its own when you only need cleanup.

Are exceptions slow in C#?

Throwing and catching an exception is far more expensive than returning a value, because it allocates and walks the stack. The cost is irrelevant for genuine errors but adds up if you throw inside a loop or use exceptions for control flow. Use Try* methods for expected failures.

Wrapping Up

try/catch/finally is the core of error handling in C#: try the risky code, catch the specific exceptions you can handle (most-specific first), and clean up in finally or with using. Add when filters for conditional handling and custom exception types when callers need to tell your failures apart. For a broader tour of the language, see the C# cheat sheet.

Thanks for reading, and please leave a comment below. Follow me on Mastodon at @khalidabuhakmeh for the latest .NET news and tutorials.

Comments

Related Posts