C# Error Handling

When a C# method cannot do its job, it throws an exception: an object describing what went wrong. The exception travels up the call stack, skipping the rest of each method, until a catch block that matches its type handles it. If nothing catches it, the program stops and prints the error. finally and using make sure cleanup still happens on the way out. This lesson covers how to catch well, how to throw well, and when not to use exceptions at all.

Exceptions

Every exception derives from System.Exception, which carries a Message, a StackTrace showing where it was thrown, and an optional InnerException — the original error when one exception is wrapped in another. You will meet these types most often:

ExceptionTypical cause
ArgumentException, ArgumentNullException, ArgumentOutOfRangeExceptiona caller passed an invalid argument
InvalidOperationExceptionthe call is not valid in the object's current state
NullReferenceExceptiona member was used on a null reference — always a bug
IndexOutOfRangeException, KeyNotFoundExceptionbad array index, missing dictionary key
FormatException, OverflowExceptionparsing or converting failed
DivideByZeroExceptioninteger division by zero (floating point gives infinity instead)
IOException, FileNotFoundException, UnauthorizedAccessExceptionfile system problems
HttpRequestException, TimeoutException, OperationCanceledExceptionnetwork calls, timeouts, cancellation

try, catch and finally

Put the code that may fail in a try block and follow it with one or more catch blocks. The runtime checks them in order and runs the first one whose type matches, so list specific types before general ones (the compiler rejects a catch that can never be reached). A finally block runs in every case — after success, after a handled exception, and even when the exception keeps propagating.

// Each input fails in a different way; finally runs every time.
int[] data = { 10, 0, 5 };

foreach (string input in new[] { "2", "1", "9", "x" })
{
    try
    {
        int index = int.Parse(input);
        Console.WriteLine($"100 / data[{index}] = {100 / data[index]}");
    }
    catch (DivideByZeroException)
    {
        Console.WriteLine($"data[{input}] is zero");
    }
    catch (IndexOutOfRangeException)
    {
        Console.WriteLine($"no element at {input}");
    }
    catch (FormatException ex)
    {
        Console.WriteLine($"bad input '{input}': {ex.GetType().Name}");
    }
    finally
    {
        Console.WriteLine($"  (checked {input})");
    }
}

Output:

100 / data[2] = 20
  (checked 2)
data[1] is zero
  (checked 1)
no element at 9
  (checked 9)
bad input 'x': FormatException
  (checked x)

This example catches exceptions to show how they work. In real code, an index that might be out of range or text that might not be a number is better checked before the operation — see When Not to Throw.

Exception Filters

A when clause adds a condition to a catch. If the condition is false, the block is skipped as if it were not there, and the exception continues to the next handler without being caught and rethrown, so the original stack trace stays intact. Filters let you handle only the cases you understand, such as one HTTP status code.

catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
    Console.WriteLine("Resource not found");     // other HTTP errors are not caught here
}

Throwing Exceptions

Throw when a method cannot fulfil its contract: an argument is invalid, the object is in the wrong state, or a resource it needs is unavailable. Pick the most specific existing type that describes the problem and write a message that helps the person reading the log: what was expected and what was received.

Guard Clauses

Validate arguments at the top of a public method, before doing any work. .NET 8 provides one-line helpers that build the right exception and message, using the parameter name automatically:

// Guard clauses reject bad arguments before any work is done.
Console.WriteLine(Repeat("ab", 3));

try
{
    Repeat("ab", -1);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: parameter '{ex.ParamName}'");
}

try
{
    Repeat("", 2);
}
catch (ArgumentException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: parameter '{ex.ParamName}'");
}

static string Repeat(string text, int times)
{
    ArgumentException.ThrowIfNullOrEmpty(text);
    ArgumentOutOfRangeException.ThrowIfNegative(times);
    return string.Concat(Enumerable.Repeat(text, times));
}

Output:

ababab
ArgumentOutOfRangeException: parameter 'times'
ArgumentException: parameter 'text'

Rethrowing and Wrapping

Sometimes a method catches an exception only to log it or add context. There are three ways to continue, and only two are correct:

  • throw; — rethrows the same exception with its original stack trace. Use it after logging.
  • throw new ConfigException("...", ex); — wraps the original as InnerException in a new exception that explains the failure at a higher level.
  • throw ex; — avoid: it restarts the stack trace at this line, erasing where the problem really happened.

Custom Exceptions

Defining and Wrapping

Create your own exception type when callers need to catch your failure specifically, separately from the general ones. Derive from Exception (not the legacy ApplicationException), end the name with Exception, and provide a constructor that accepts an inner exception so wrapping preserves the cause.

// Wrap a low-level IOException in a domain exception that keeps the cause.
try
{
    LoadConfig("missing.json");
}
catch (ConfigException ex) when (ex.InnerException is FileNotFoundException)
{
    Console.WriteLine(ex.Message);
    Console.WriteLine($"cause: {ex.InnerException?.GetType().Name}");
}

static string LoadConfig(string path)
{
    try
    {
        return File.ReadAllText(path);
    }
    catch (IOException ex)                   // FileNotFoundException is an IOException
    {
        throw new ConfigException($"Cannot load config '{path}'", ex);
    }
}

class ConfigException : Exception
{
    public ConfigException(string message) : base(message) { }
    public ConfigException(string message, Exception inner) : base(message, inner) { }
}

Output:

Cannot load config 'missing.json'
cause: FileNotFoundException

Cleanup with using

IDisposable and Dispose Order

Files, network connections and database handles must be released even when an error occurs. Such types implement IDisposable, and the using statement calls their Dispose method automatically, exactly as if you had written a finally block. The short form using var x = ...; disposes at the end of the enclosing block. Several resources are disposed in reverse order of creation.

// using guarantees Dispose runs, also when an exception leaves the block.
using (var log = new Resource("log"))
{
    Console.WriteLine("writing log");
}

try
{
    using var db = new Resource("db");       // disposed when the try block exits
    throw new InvalidOperationException("query failed");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"caught: {ex.Message}");
}

sealed class Resource : IDisposable
{
    private readonly string _name;

    public Resource(string name)
    {
        _name = name;
        Console.WriteLine($"{name} opened");
    }

    public void Dispose() => Console.WriteLine($"{_name} disposed");
}

Output:

log opened
writing log
log disposed
db opened
db disposed
caught: query failed

Note the order: db is disposed before the catch block runs, because leaving the try block ends the resource's scope. Asynchronous resources implement IAsyncDisposable and use await using.

Best Practices

When Not to Throw

Exceptions are for exceptional situations. They are slow compared with an if, and code that uses them for normal control flow is hard to follow. When failure is an expected outcome, return it instead:

  • The Try pattern: bool TryParse(string s, out int value), dictionary.TryGetValue(key, out var v). Use it for user input and lookups. See Type Casting.
  • A nullable result: FirstOrDefault() returning null when nothing matches, with the nullable context making the caller check.
  • A result type — for example a sealed record hierarchy with Success and Failure cases — when the caller must handle several kinds of failure.

Do Not Swallow Exceptions

  • Never write an empty catch { }. A failure that nobody hears about becomes corrupt data or a mystery bug weeks later.
  • Catch Exception only at the edge of the program — in Main, a request handler, a background job loop — to log the error and keep serving or exit cleanly.
  • Do not catch exceptions that reveal bugs (NullReferenceException, IndexOutOfRangeException) to "make them go away"; fix the code.
  • Log the whole exception (ex.ToString()), not just ex.Message, so the stack trace and inner exceptions are kept.
  • In async code, an exception from an awaited task is rethrown at the await, so the same try/catch works. Cancellation arrives as OperationCanceledException and usually should not be logged as an error. See High Performance Computing for tasks.

The demo 15_error_handling.cs collects these patterns in one program.

Practice

Exercises

  1. Rewrite the first example so that it never throws: check the index range and use int.TryParse, keeping the same output.
  2. In LoadConfig, replace throw new ConfigException(...) with throw; and then with throw ex;, print ex.StackTrace in each case, and compare.
  3. Write a Withdraw method that throws a custom InsufficientFundsException carrying the Balance and the requested Amount as properties.
  4. Wrap a whole program in a top-level try/catch (Exception ex) that prints the error to Console.Error and returns exit code 1.