Exceptions in C#: try, catch, finally and throw

Lesson 10 of 15 · C#

An exception is an error that occurs while a program is running: the user enters letters instead of a number, a number is divided by zero, an element outside an array is requested… Without handling, an exception stops the program. The try and catch blocks let the program "catch" the error, handle it and keep running.

Before you start: required prior knowledge – collections, classes and objects.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.

Catching exceptions: try and catch

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a number: ");
        try
        {
            int x = int.Parse(Console.ReadLine());   // can throw a FormatException
            Console.WriteLine($"100 / {x} = {100 / x}");   // can throw a DivideByZeroException
        }
        catch (FormatException)
        {
            Console.WriteLine("Error: that is not a whole number.");
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Error: division by zero.");
        }
        Console.WriteLine("The program keeps running.");
    }
}

When an exception occurs in the try block, the rest of the block is skipped and the first catch whose type matches is looked for. After the handling, the program continues after the whole try-catch. The most common exceptions are shown in the table:

ExceptionWhen it occurs
FormatExceptionthe text is not in the expected form (int.Parse("abc"))
DivideByZeroExceptioninteger division by zero
IndexOutOfRangeExceptionan index outside the bounds of an array
ArgumentOutOfRangeExceptionan index outside the bounds of a list or a string
NullReferenceExceptionusing a variable whose value is null
KeyNotFoundExceptionreading a key that does not exist in a dictionary
OverflowExceptionthe number does not fit in the type (for example int.Parse("99999999999"))

The finally block and the exception object

The finally block is executed always – both when there is no exception and when one has been caught. It is used for "cleaning up": closing a file, a database connection… After the type in catch you can write a variable name, and then you get the exception object with data about the error.

using System;

class Program
{
    static void Main()
    {
        int[] array = { 10, 20, 30 };
        for (int i = 2; i <= 3; i++)
        {
            try
            {
                Console.WriteLine($"array[{i}] = {array[i]}");
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine($"Caught exception: {e.GetType().Name}");
            }
            finally
            {
                Console.WriteLine($"finally for i = {i}");
            }
        }
    }
}

The property e.Message contains a description of the error (in the language of the operating system), and catch (Exception e) catches an exception of any type – that is why it is written last, after the more specific ones.

An exception or a check in advance?

Catching exceptions is slower and less clear than an ordinary check. When an error can be foreseen – such as wrong input – it is better to check in advance, for example with the TryParse method. Exceptions are for situations that cannot easily be checked.

using System;

class Program
{
    // repeats the input until the user enters a whole number in the range [min, max]
    static int ReadNumber(string message, int min, int max)
    {
        while (true)
        {
            Console.Write(message);
            if (int.TryParse(Console.ReadLine(), out int x) && x >= min && x <= max)
                return x;
            Console.WriteLine($"Enter a whole number from {min} to {max}.");
        }
    }

    static void Main()
    {
        int grade = ReadNumber("Grade: ", 1, 5);
        Console.WriteLine($"Grade entered: {grade}");
    }
}

Throwing an exception: throw

Our own code can also throw an exception with the throw statement, when a method gets data it cannot work with. This way the method does not have to print messages itself – the error is reported to whoever called the method.

using System;

class Account
{
    public decimal Balance { get; private set; }

    public void Deposit(decimal amount) => Balance += amount;

    public void Withdraw(decimal amount)
    {
        if (amount <= 0)
            throw new ArgumentException("The amount must be positive.");
        if (amount > Balance)
            throw new InvalidOperationException($"Not enough money (balance: {Balance}).");
        Balance -= amount;
    }
}

class Program
{
    static void Main()
    {
        var a = new Account();
        a.Deposit(500);
        decimal[] requests = { 200, -50, 1000, 300 };
        foreach (decimal r in requests)
        {
            try
            {
                a.Withdraw(r);
                Console.WriteLine($"Withdrawn {r}, balance {a.Balance}");
            }
            catch (ArgumentException e)
            {
                Console.WriteLine("Rejected: " + e.Message);
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine("Rejected: " + e.Message);
            }
        }
    }
}

Your own exception

Your own exception is a class that inherits the class Exception. By convention its name ends with Exception, and the message is passed to the base class constructor with : base(message). The same approach is used in the advanced example with train passengers.

using System;
using System.Collections.Generic;

class CapacityExceededException : Exception
{
    public int Capacity { get; }

    public CapacityExceededException(int capacity)
        : base($"The capacity of {capacity} seats has been exceeded.")
    {
        Capacity = capacity;
    }
}

class Bus
{
    private readonly List<string> passengers = new List<string>();
    private readonly int capacity;

    public Bus(int capacity) { this.capacity = capacity; }

    public int Count => passengers.Count;

    public void Board(string name)
    {
        if (passengers.Count == capacity)
            throw new CapacityExceededException(capacity);
        passengers.Add(name);
    }
}

class Program
{
    static void Main()
    {
        var bus = new Bus(3);
        string[] line = { "Anna", "Bob", "Cindy", "Dan", "Emma" };
        try
        {
            foreach (string name in line)
            {
                bus.Board(name);
                Console.WriteLine($"{name} got on.");
            }
        }
        catch (CapacityExceededException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine($"On the bus: {bus.Count}");
        }
    }
}

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: easy

The sum of the valid numbers

A line contains words separated by spaces. Add up all the words that are whole numbers and count the ones that are not.

Example

Input

5 abc 12 7.5 -3 x

Output

Sum: 14
Invalid: 3
TASK 02Difficulty: medium

Calculator

Each line of the input has the form a op b (whole numbers and an operation + - * /), and the input ends with the line end. For each line print the result (division is integer division) or the message Error: invalid number, Error: division by zero or Error: unknown operation X. Handle the errors with exceptions.

Example

Input

8 + 5
7 / 0
9 ^ 2
12 * x
20 / 6
end

Output

13
Error: division by zero
Error: unknown operation ^
Error: invalid number
3
Common mistakes and tips
  • Catch only the exceptions you know how to handle; an empty catch { } hides errors.
  • More specific catch blocks come before more general ones (catch (Exception) is last).
  • Check foreseeable errors (input) in advance – TryParse is better than catching a FormatException.
  • The name of your own exception ends with Exception, and the class inherits Exception.

Check your knowledge

Open the quiz

Exceptions in C#

1. Which exception does int.Parse("abc") throw?




2. When is the finally block executed?




3. With which statement does a method report an error itself?




4. Which class does your own exception inherit?