TExcelTAD
Home › C# › C# Exceptions

C# Exceptions

Things go wrong at run time: a file is missing, a user types letters where a number belongs, a network drops, a division by zero sneaks in. C# reports such problems with exceptions — objects that describe the error and interrupt the normal flow of the program until some code catches them. An exception that nobody catches terminates the program.

try and catch

Put code that might fail in a try block, and handle the failure in a catch block:

csharp · try it yourself
using System;

int[] numbers = { 1, 2, 3 };

try
{
    Console.WriteLine("Before");
    Console.WriteLine(numbers[10]);     // throws
    Console.WriteLine("Never printed");
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine(
quot;Caught: {ex.Message}"); } Console.WriteLine("Program continues");
Before
Caught: Index was outside the bounds of the array.
Program continues

As soon as the exception is thrown, the rest of the try block is skipped and control jumps to the matching catch.

Catching different exception types

All exceptions derive from System.Exception. You can have several catch blocks; the first one whose type matches handles the exception, so list specific types before general ones.

csharp · try it yourself
using System;

string[] inputs = { "10", "zero", "0", "99999999999" };

foreach (string input in inputs)
{
    try
    {
        int n = int.Parse(input);
        Console.WriteLine(
quot;100 / {n} = {100 / n}"); } catch (FormatException) { Console.WriteLine(
quot;'{input}' is not a number"); } catch (DivideByZeroException) { Console.WriteLine("Cannot divide by zero"); } catch (Exception ex) { Console.WriteLine(
quot;Other problem: {ex.GetType().Name}"); } }
100 / 10 = 10
'zero' is not a number
Cannot divide by zero
Other problem: OverflowException

Common built-in exceptions:

Exception Typical cause
NullReferenceException Using a member of a null reference
IndexOutOfRangeException Array index outside its bounds
ArgumentException / ArgumentNullException / ArgumentOutOfRangeException A method received an invalid argument
InvalidOperationException The object is in the wrong state for the call
FormatException Text could not be parsed
DivideByZeroException Integer division by zero
KeyNotFoundException Dictionary key does not exist
FileNotFoundException / IOException File system problems

finally

A finally block runs whether or not an exception occurred — even if the try block returns. It is used for cleanup such as closing files or connections.

csharp · try it yourself
using System;

static int Divide(int a, int b)
{
    try
    {
        Console.WriteLine(
quot;Dividing {a} by {b}"); return a / b; } catch (DivideByZeroException) { Console.WriteLine("Division failed"); return 0; } finally { Console.WriteLine("Cleanup done"); } } Console.WriteLine(Divide(10, 2)); Console.WriteLine(Divide(1, 0));
Dividing 10 by 2
Cleanup done
5
Dividing 1 by 0
Division failed
Cleanup done
0

For objects that implement IDisposable (files, streams, database connections), the using statement is a shorter way to get the same guarantee: using var file = File.OpenText(path); disposes the file at the end of the scope.

Throwing exceptions

Use throw to signal that your own code cannot continue. Pick the most fitting built-in exception type and write a helpful message:

csharp · try it yourself
using System;

static decimal Withdraw(decimal balance, decimal amount)
{
    if (amount <= 0)
        throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive.");
    if (amount > balance)
        throw new InvalidOperationException(
quot;Insufficient funds: balance {balance}, requested {amount}."); return balance - amount; } try { Console.WriteLine(Withdraw(100m, 30m)); Console.WriteLine(Withdraw(100m, 500m)); } catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }
70
Insufficient funds: balance 100, requested 500.

Custom exceptions and filters

For domain-specific errors, derive your own class from Exception. A when clause (an exception filter) catches an exception only if a condition is true:

csharp · try it yourself
using System;

try
{
    PlaceOrder("SKU-1", 0);
}
catch (OrderException ex) when (ex.Code == 1)
{
    Console.WriteLine(
quot;Quantity problem: {ex.Message}"); } catch (OrderException ex) { Console.WriteLine(
quot;Other order problem: {ex.Message}"); } static void PlaceOrder(string sku, int quantity) { if (quantity <= 0) throw new OrderException(1,
quot;Cannot order {quantity} of {sku}."); } class OrderException : Exception { public int Code { get; } public OrderException(int code, string message) : base(message) => Code = code; }
Quantity problem: Cannot order 0 of SKU-1.

Inside a catch block, a bare throw; re-throws the current exception while preserving its original stack trace — prefer it over throw ex;.

Good practices

  • Catch exceptions only where you can actually do something about them (retry, show a message, use a fallback).
  • Don't use exceptions for normal control flow. int.TryParse is better than catching FormatException for user input.
  • Never silently swallow exceptions with an empty catch { } — at least log them.
  • Prefer specific exception types over catching Exception everywhere.

Test yourself

When does a finally block run?

  1. Only if an exception occurred
  2. Only if no exception occurred
  3. Always, after try/catch
  4. Only when the program exits

Why should catch (Exception) come after more specific catch blocks?

  1. It is faster
  2. The first matching catch wins, so a general one first would hide the specific ones
  3. It is required by the runtime only in Release builds
  4. It does not matter

What is the best way to re-throw the exception you just caught?

  1. throw ex;
  2. throw;
  3. throw new Exception();
  4. return ex;