Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

Exception handling best practices

Practical guidance for C# exception handling: throw specific types, keep stack traces, avoid swallowing errors, use Try methods, finally and using, and log once.

Exceptions are for situations your code cannot handle at the point where they occur. Used well they keep the normal path clean and carry enough information to diagnose a failure. Used badly they hide bugs, slow programs down and make logs unreadable. This page collects the rules that matter most in everyday C#.

The common theme: throw early and specifically, catch late and only what you can handle, and never lose information on the way.

C#
try
{
    ProcessOrder(order);
}
catch (PaymentDeclinedException e)
{
    NotifyCustomer(e);   // a failure we know how to handle
}

Try it

C# Wrap, do not swallow, and keep the cause

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# Rethrow correctly and always clean up

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.

Rules of thumb

Do Avoid
Throw the most specific built-in type, or a custom one with data throw new Exception("...")
Use throw; to rethrow throw e; (resets the stack trace)
Pass the original as innerException when wrapping Creating a new exception that drops the cause
Use TryParse, TryGetValue, Dictionary lookups for expected misses Using exceptions as normal control flow
Use using or finally for cleanup Relying on callers or finalizers to release resources
Catch what you can actually handle catch (Exception) { } that swallows everything
Validate arguments first with ThrowIfNull and friends Letting a bad argument fail deep in the call chain

Returns / errors: this is a guideline page, so there is no single API. The sections below explain the reasoning.

Usage notes

  • Throw for exceptional conditions only. A missing file in a config folder may be expected; a user mistyping a number is expected. Use Try... methods or return values for those. Throwing costs microseconds, versus nanoseconds for a branch, and a debugger set to break on exceptions turns them into noise.
  • Never throw e;. It resets the stack trace and hides where the problem started. Use throw; inside the catch, or ExceptionDispatchInfo when you rethrow elsewhere.
  • Catch late, near a boundary. Let exceptions bubble to the layer that can do something: retry, show a message, return an HTTP 500. Low-level code usually should not catch at all.
  • Log once. Logging at every level produces duplicate entries. Log where you handle the exception, or at the top-level handler, and include the exception object (logger.LogError(e, "message")), not only e.Message.
  • Do not catch Exception unless you rethrow or are at the top level. Also never catch and ignore OutOfMemoryException or StackOverflowException; the latter cannot be caught anyway (StackOverflow).
  • Use filters to catch narrowly. catch (HttpRequestException e) when (e.StatusCode == HttpStatusCode.NotFound) leaves other errors alone. See Exception filters.
  • Respect cancellation. Do not treat OperationCanceledException as a failure, and do not swallow it in catch-all blocks.
  • Do not return null after catching just to avoid the exception. Callers then fail later with a NullReferenceException that is harder to explain.
  • Use finally or using for cleanup. Never return from a finally block; it silently discards exceptions.
  • Async code. Always await tasks so exceptions surface; avoid async void except for event handlers; remember that await Task.WhenAll throws only the first exception (AggregateException).
  • Do not leak sensitive data (passwords, tokens, personal data) into messages. Exception text goes to logs and sometimes to users.
  • Document what you throw. Use /// <exception cref="..."> on public members so callers know what to catch.