Lesson 19 of 24

In progress

Course progress

C# and .NET

Exceptions and error handling

Catch what you can handle, wrap with the original cause, and use filters and finally without hiding failures.

C# exceptions are all unchecked: the compiler does not force you to catch them. That makes the language simpler and puts the responsibility on you to decide which failures are recoverable.

What you will learn

  • Catch specific exceptions and let the rest propagate.
  • Use when filters and finally correctly.
  • Write messages that name the problem and the value.

The hierarchy

All exceptions derive from Exception. The common ones:

  • ArgumentException, ArgumentNullException, ArgumentOutOfRangeException — bad input from a caller.
  • InvalidOperationException — the object or system is in the wrong state.
  • NullReferenceException — a bug, not a condition to handle.
  • IOException and its subclasses — file and stream failures.
  • FormatException — text that does not match the expected shape.

Throwing the specific type is what lets a caller catch precisely what it can recover from.

Catching

try
{
int qty = int.Parse(input);
Console.WriteLine(qty);
}
catch (FormatException ex)
{
Console.WriteLine($"not a number: {input}");
}

Catch the most specific type you can handle. catch (Exception ex) catches everything, including bugs you did not anticipate, and continuing after those usually leaves the program in a worse state.

Multiple catches are checked in order, so derived types must come first:

try
{
var text = File.ReadAllText(path);
}
catch (FileNotFoundException)
{
Console.WriteLine("missing file");
}
catch (IOException ex)
{
Console.WriteLine($"read failed: {ex.Message}");
}

Exception filters

catch (IOException ex) when (ex.HResult == -2147024864)
{
Console.WriteLine("file is locked by another process");
}

A when filter inspects the exception before deciding to catch it. If the filter is false, the exception continues as if this catch did not exist, which lets you handle one specific case and leave the rest to a higher layer.

That is far better than catching broadly and rethrowing conditionally, which resets the stack trace.

Rethrowing

catch (IOException ex)
{
logger.Error("read failed", ex);
throw;              // keeps the original stack trace
}

throw; preserves the trace. throw ex; resets it to this line, which destroys the information you need to find the cause. The difference is worth remembering because both compile.

Wrapping

public Order Load(int id)
{
try
{
return repository.Get(id);
}
catch (IOException ex)
{
throw new OrderLoadException($"could not load order {id}", ex);
}
}

A custom exception with the original as the inner exception adds context without losing the cause. ex.InnerException and the printed trace both survive.

Losing the cause — throw new OrderLoadException("failed") — is worse than not catching at all.

finally and using

FileStream? stream = null;
try
{
stream = File.OpenRead(path);
Use(stream);
}
finally
{
stream?.Dispose();
}

finally runs whether or not an exception occurred. In modern C#, using does the same with less code:

using var stream = File.OpenRead(path);
Use(stream);

using var disposes at the end of the enclosing scope; using (...) disposes at the end of the block. Both replace the manual finally for IDisposable resources.

Do not return from finally: it discards the exception and the pending return value.

Custom exceptions

public class InsufficientStockException : Exception
{
public string Sku { get; }
public InsufficientStockException(string sku)
: base($"no stock for {sku}")
{
Sku = sku;
}
}

Extend Exception (or a more specific type), pass a message to the base constructor, and add data the handler needs. Keep the set small: one per recovery path, not one per method.

Messages

throw new ArgumentOutOfRangeException(nameof(quantity), quantity,
"quantity must be at least 1");

That constructor includes the parameter name, the value and the rule. A message like "invalid quantity" repeats what the type already says and omits the value that would explain the failure.

Anti-patterns

  • Swallowing: an empty catch hides the failure and leaves bad state.
  • Log and rethrow at every level: duplicate log entries and no clear owner.
  • Exceptions for control flow: parsing with exceptions in a loop is slow and obscure; use TryParse.
  • Catching NullReferenceException: it is a bug; fix the null.
  • Throwing in a constructor for a condition the caller should check first: prefer a Try factory when failure is expected.

Designing the boundary

At the edge — a request handler, Main — catch, log with context, and return an error the caller can act on. Inside the application, let exceptions propagate to the layer that understands them.

That keeps every layer from knowing about every failure, and a new exception type is handled in one place rather than five.

Catching an exception, logging it, and returning a default value. The caller cannot distinguish success from failure, and the missing data appears much later in a report.

Write a method that parses a list of strings into integers, skipping invalid entries, and reports how many were skipped. Use TryParse rather than exceptions.

Show solution
static (List<int> values, int skipped) ParseAll(IEnumerable<string> inputs) { var values = new List<int>(); int skipped = 0; foreach (var input in inputs) { if (int.TryParse(input, out int value)) { values.Add(value); } else { skipped++; } } return (values, skipped); }

TryParse treats bad input as an expected outcome, which it is for user data. The tuple reports both results, so the caller can log the count without the method deciding what to do about it.

Recap

  • Catch specific exceptions; let bugs propagate and handle failures where you can act.
  • throw; keeps the stack trace; wrapping keeps the inner exception.
  • using and finally guarantee cleanup; messages should name the value and the rule.

Next, files: reading, writing and the paths that make it work anywhere.

Should I catch Exception at the top level?
Yes, at the process or request boundary, to log and return a controlled error. Not in the middle of the application.
What is the difference between throw and throw ex?
`throw` preserves the original stack trace; `throw ex` resets it to the current line.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.