IC Improve Code Recipes

Recipe 5.1 · C#

No Empty Catch Blocks

Problem

A catch { } or catch (Exception) { } throws away the only evidence that something failed. The code carries on with half-finished work: a file that wasn't written, a row that wasn't saved, a customer who wasn't billed. Nobody finds out until the numbers don't add up.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: three ways to hide a failure.
try
{
    price = decimal.Parse(fields[3]);
}
catch { price = 0; }          // bad data becomes a free product

try
{
    File.Delete(tempPath);
}
catch (Exception) { }         // also hides a typo in the path

try
{
    SaveOrder(order);
}
catch (Exception ex)
{
    lblError.Text = ex.Message; // the user sees it; nobody else does
}

The improved recipe

Every catch must do one of four things: recover with a known fallback, translate the exception into one with more context, log it at a boundary, or clean up and rethrow. Expected bad input should not use exceptions at all.

C#
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using Microsoft.Extensions.Logging;

namespace ImproveCode.Errors;

public sealed record PriceRow(string Sku, decimal Price);

public sealed class PriceFileReader(ILogger<PriceFileReader> logger)
{
    public IReadOnlyList<PriceRow> Read(string path)
    {
        var rows = new List<PriceRow>();
        int lineNumber = 0;

        // Missing file or no permission: let it propagate.
        // The caller decides; we have nothing useful to add.
        foreach (string line in File.ReadLines(path))
        {
            lineNumber++;

            // Bad data is expected, so it is not an exception.
            if (TryParse(line, out PriceRow? row))
            {
                rows.Add(row);
            }
            else
            {
                logger.LogWarning(
                    "Skipped line {LineNumber} of {FileName}: {Line}",
                    lineNumber, Path.GetFileName(path), line);
            }
        }

        return rows;
    }

    public void DeleteQuietly(string path)
    {
        try
        {
            File.Delete(path);
        }
        catch (Exception ex)
            when (ex is IOException or UnauthorizedAccessException)
        {
            // Recover: a locked temp file is removed on the next run.
            logger.LogDebug(ex, "Could not delete {Path}", path);
        }
    }

    private static bool TryParse(
        string line, [NotNullWhen(true)] out PriceRow? row)
    {
        row = null;
        string[] fields = line.Split(',');
        if (fields.Length != 2 || fields[0].Length == 0)
        {
            return false;
        }

        if (!decimal.TryParse(fields[1], NumberStyles.Number,
                CultureInfo.InvariantCulture, out decimal price)
            || price < 0)
        {
            return false;
        }

        row = new PriceRow(fields[0].Trim(), price);
        return true;
    }
}

How it works

Read has no try at all. If the file is missing, File.ReadLines throws FileNotFoundException with the path in the message, and that is exactly what the caller and the log need. Catching it here only to rethrow or return an empty list would make things worse: an empty list looks like "no prices today."

Bad lines are an expected condition in any imported file, so the code tests for them with TryParse instead of catching FormatException. That is faster, and it keeps exceptions for things that are truly unexpected. The warning records the line number and content, so the person who sent the file can fix it.

DeleteQuietly is a legitimate recovery. Failing to delete a temp file is harmless, and there is a fallback (the next run tries again). The exception filter limits the catch to the two exception types that mean "locked" or "no permission." A NullReferenceException from a bug, or an ArgumentException from an invalid path, still escapes. The comment says why swallowing is safe, and the debug log keeps a trail.

The rule of thumb: catch only what you can name, and only where you can do something about it. Everywhere else, let the exception travel up to the global handler (Recipe 5.4) or the job runner (Chapter 4, Recipe 4.6), which logs it once with full context.

Variations and pitfalls

  • catch (Exception) is fine at a true boundary: the top of a request, a background job loop, a message handler. Those places must log and keep the process alive. Deep inside business logic it almost always hides bugs.
  • Never catch OperationCanceledException as a failure. If the caller cancelled, let it go. When you do catch it, filter with when (ct.IsCancellationRequested).
  • Displaying ex.Message to users leaks internals (table names, file paths, server names) and does nothing for support. Show a reference number instead and log the details (Recipe 5.4).
  • To find the empty catches in a code base, search for catch\s*(\(\s*Exception\s*\w*\s*\))?\s*\{\s*\} with your editor's regex search, then review each one. Most can simply be deleted.
  • Turn on analyzer rule CA1031 (do not catch general exception types) in new projects and suppress it, with a comment, at the few real boundaries.