Exceptions: try, catch, finally, using and Custom Errors
Learn how C# reports errors with exceptions, how to catch, filter and rethrow them, how using and IDisposable clean up in reverse order, and how to write a custom exception, with real ordered output.
In this lesson you will
- Throw, catch and filter exceptions
- Use finally and using
- Write a custom exception
- Predict the order of events
About 28 minutes
When an order cannot be read
Omar’s till program reads each order from a text line, and one morning a line contains “x3” where a number should be. Without a plan the program stops with a long red message and the whole queue waits. An exception is an object that .NET creates when something goes wrong. It travels up through the callers until some code catches it, or the program ends. Handling exceptions well means deciding, for each failure, who can do something useful about it.
Code that might fail goes in a try block. A catch block handles one kind of exception, and an optional when clause, an exception filter, adds a condition. A finally block runs whatever happens, which is the place to release resources. The using statement makes this easier: a variable declared with using var is disposed at the end of its scope, even when an exception is thrown, if its type implements IDisposable. Disposal happens in the reverse order of declaration. Unlike Java, C# has no checked exceptions, so the compiler does not force you to catch anything, and it is your job to know which failures are likely. For failures that are normal, such as text that is not a number, prefer methods like int.TryParse that return a flag and do not throw.
| Part | Use |
|---|---|
| try / catch (Type e) | Handle a specific failure |
| catch … when (condition) | Handle only when a condition holds |
| finally | Cleanup that must always run |
| using var x = … | Dispose x at the end of the scope, in reverse order |
| throw; | Rethrow, keeping the original stack trace |
| TryParse | Avoid exceptions for expected bad input |
var log = new List<string>();
string Book(string bike, string days)
{
try
{
int d = int.Parse(days);
if (d < 1) throw new ArgumentOutOfRangeException(nameof(days), "days must be positive");
return $"{bike}: {d * 12} euro";
}
catch (FormatException e)
{
throw new OrderException($"cannot read '{days}'", bike, e);
}
}
foreach (var (bike, days) in new[] { ("City 1", "3"), ("Trail 2", "x3"), ("Tandem 3", "0") })
{
try { Console.WriteLine(Book(bike, days)); }
catch (OrderException e) { Console.WriteLine($"OrderException for {e.Bike}: {e.Message} (cause: {e.InnerException!.GetType().Name})"); }
catch (ArgumentOutOfRangeException e) when (e.ParamName == "days") { Console.WriteLine($"filtered: {e.ParamName} problem"); }
finally { Console.WriteLine($" finished {bike}"); }
}
try
{
using var a = new Tracer("A", log);
using var b = new Tracer("B", log);
log.Add("body");
throw new InvalidOperationException("boom");
}
catch (InvalidOperationException e) { log.Add($"caught {e.Message}"); }
Console.WriteLine(string.Join(", ", log));
Console.WriteLine($"TryParse avoids the exception: {int.TryParse("x3", out var n)} -> {n}");
class OrderException : Exception
{
public string Bike { get; }
public OrderException(string message, string bike, Exception inner) : base(message, inner) { Bike = bike; }
}
class Tracer : IDisposable
{
readonly string name; readonly List<string> log;
public Tracer(string name, List<string> log) { this.name = name; this.log = log; log.Add("open " + name); }
public void Dispose() => log.Add("close " + name);
}
City 1: 36 euro
finished City 1
OrderException for Trail 2: cannot read 'x3' (cause: FormatException)
finished Trail 2
filtered: days problem
finished Tandem 3
open A, open B, body, close B, close A, caught boom
TryParse avoids the exception: False -> 0
The first order worked and printed 36 euro. The second failed in int.Parse with a FormatException, which the Book method caught and wrapped in our own OrderException, keeping the original as the inner exception, so the report says both what we were doing and what failed. The third, with 0 days, raised an ArgumentOutOfRangeException, and the filter when (e.ParamName == “days”) let that catch block handle it only for the parameter we expected. The finally block ran 3 times, once per order, whatever happened.
The using part shows the order. The log reads “open A, open B, body, close B, close A, caught boom”: A and B were opened in that order, the body ran and threw, then B was disposed before A, and only afterwards did the catch block run. That is why using is safer than closing resources by hand: nobody can forget, and a failure in the body does not leak the resource. The last line shows that int.TryParse returned false for “x3” and gave the value zero, without any exception at all, which is the better tool when bad input is normal and not exceptional.
Check by hand: 3 days at 12 euro is 36. int.Parse cannot read an x, so a FormatException is certain. For the log, disposal runs in the reverse order of declaration, so B closes before A, and the catch runs after the try block has been left and its using variables disposed.
A broad catch with an empty body hides bugs. Catch the specific types you can handle, log the rest and let them propagate.
Writing throw e resets the stack trace. Writing throw; keeps it, which makes the cause far easier to find.
Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8.
Practice
Write a method that parses a price and throws a custom exception for a negative value. Call it in a loop over several strings, count the failures, and then rewrite it with TryParse and compare the two designs. Add a using declaration for a StreamWriter on a temporary file.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does finally guarantee?
- It runs whether or not an exception happened
- It runs only on error
- It runs only on success
- It never runs
Use it for cleanup.
In which order does using dispose variables?
- Declaration order
- Alphabetical
- Random
- Reverse of declaration
B closed before A.
What does a when clause on a catch do?
- Delays the exception
- Closes a file
- Changes the type
- Adds a condition for handling
An exception filter.
Why wrap an exception in a custom one?
- To hide it
- To speed up the program
- To add context and keep the cause
- To make it checked
InnerException holds the original.
When should you prefer TryParse?
- Never
- Only for dates
- When bad input is normal
- Only for files
No exception is created.
Summary
- Exceptions travel up the call stack until caught.
- finally and using clean up, and using disposes in reverse order.
- Custom exceptions add context and keep the cause.
- Use TryParse for expected bad input.
Questions
What is the difference between throw and throw e?
throw rethrows the current exception and keeps its stack trace. throw e starts a new trace from that line.
What is IDisposable?
An interface with a Dispose method for releasing resources such as files and connections. using calls it for you.
Does C# have checked exceptions?
No. The compiler does not force you to catch exceptions, so document and test the failures that matter.
