Exception Handling in C#
Learn the basics of exception handling in C# using try, catch, and finally blocks to handle runtime errors gracefully.
What is an Exception?
An exception is a runtime error that disrupts the normal flow of a program, such as dividing by zero or accessing a null reference.
The try-catch Block
Code that might throw an error is placed inside a try block, while a matching catch block defines how to handle that specific error if it occurs.
The finally Block
A finally block contains code that always runs after the try and catch blocks, regardless of whether an exception occurred, making it ideal for cleanup tasks.
Throwing Exceptions
The throw keyword is used to raise an exception explicitly, either a built-in exception type or a custom one, when your code detects an invalid situation.
A Complete try, catch and finally Example
The program below reads a number from a file and divides 100 by it. Several different things can go wrong, so it handles each case separately, from the most specific exception to the most general:
using System;
using System.IO;
class Program
{
static void Main()
{
StreamReader reader = null;
try
{
reader = new StreamReader("input.txt");
int divisor = int.Parse(reader.ReadLine());
Console.WriteLine(100 / divisor);
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File missing: {ex.FileName}");
}
catch (FormatException)
{
Console.WriteLine("The file does not contain a valid number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("The number cannot be zero.");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
reader?.Dispose(); // runs whether or not an error happened
}
}
}
Order matters. C# checks catch blocks from top to bottom and runs the first one that matches. A catch (Exception) placed first would swallow everything, and the compiler reports an error for later blocks it can never reach.
using Statements, Filters and Custom Exceptions
For anything that implements IDisposable, a using statement is a shorter, safer replacement for a manual finally block. It disposes the object even when an exception is thrown:
using var reader = new StreamReader("input.txt");
string firstLine = reader.ReadLine();
Exception filters let you catch an exception only when a condition is true, which keeps catch blocks small:
catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
Console.WriteLine("Resource not found.");
}
When built-in types do not describe your problem well, create your own by inheriting from Exception:
public class InsufficientBalanceException : Exception
{
public InsufficientBalanceException(string message) : base(message) { }
}
if (amount > balance)
throw new InsufficientBalanceException("Balance is too low for this withdrawal.");
Rethrowing Correctly and Other Common Errors
- Use
throw;notthrow ex;when rethrowing inside a catch block. The first keeps the original stack trace; the second resets it and hides where the error started. - Do not leave catch blocks empty. At minimum log the error, or the bug becomes invisible.
- Avoid exceptions for normal flow. Checking user input with
int.TryParseis faster and clearer than catchingFormatExceptionevery time. - Catch only what you can handle. Let other exceptions travel up to a central handler that logs them.
- Await tasks inside try. In async code, exceptions surface when the task is awaited, so the
awaitmust be inside the try block.
Practical Checklist
- Specific catch blocks first, general last.
- Resources released with
usingor finally. - Meaningful messages, with the original exception passed as an inner exception when wrapping.
- No silent failures.
Where to Put Your Handlers
Beginners often wrap every single method in try and catch. A cleaner design catches exceptions in two kinds of places: close to the problem, when you can actually recover (for example retrying a network call or asking the user for new input), and at the top of the application, where one central handler logs anything unexpected and shows a friendly message. In ASP.NET Core, that top-level role is played by exception-handling middleware, so controllers stay short and readable.