Practical 8: Exceptions

CAB201 - Programming Principles

School of Computer Science, Faculty of Science

Exceptions in C#

An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions.

Can be caused by a variety of undesirable events, such as:

  • Division by zero
  • Attempting to access an array element that is out of bounds
int[] numbers = { 1, 2, 3 };
int x = numbers[3]; // Throws an IndexOutOfRangeException
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Throwing an Exception explicitly

You can also throw exceptions explicitly using the throw keyword.

class BankAccount {
    public double Balance { get; private set; }
    public BankAccount(double initialBalance) {
        // What if initialBalance is negative?
        // Click "Next" to see the solution
        Balance = initialBalance;
    }
}
class BankAccount {
    public double Balance { get; private set; }
    public BankAccount(double initialBalance) {
        if (initialBalance < 0) {
            throw new ArgumentException("Initial balance must be non-negative");
        }
        Balance = initialBalance;
    }
}

This can be useful for enforcing constraints on the inputs to your methods.

CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Handling Exceptions

When an exception is thrown, the program will terminate unless the exception is caught and handled.

try {
    // Code that might throw an exception
} catch (Exception e) {
    // What to do if an exception is thrown
} finally {
    // Code that always runs
}
// Click "Next" to see an example
try {
    Account account = new Account(-100);
} catch (ArgumentException e) {
    Console.WriteLine($"An error has occurred: {e.Message}");
} finally {
    Console.WriteLine("Attempted to create an account");
}
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Catching Specific Exceptions

You can catch specific types of exceptions by specifying the type of exception in the catch block.

try {
    // Code that might throw an exception
} catch (ArgumentException e) {
    // Handle ArgumentException
} catch (IndexOutOfRangeException e) {
    // Handle IndexOutOfRangeException
} catch (Exception e) {
    // Handle any other exception
}
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Common Exceptions

Exception Type Description
ArgumentException Thrown when an argument is invalid
IndexOutOfRangeException Thrown when an array index is out of bounds
NullReferenceException Thrown when trying to access a member of a null object
DivideByZeroException Thrown when dividing by zero
FileNotFoundException Thrown when a file is not found
CAB201 - Programming Principles
School of Computer Science, Faculty of Science

Custom Exceptions

If none of the built-in exceptions are suitable for your needs, you can create your own custom exception types.

A custom exception is a class that inherits from the Exception class, which has several constructors that allow you to specify the message and inner exception.

class InsufficientFundsException : Exception {
    public InsufficientFundsException() : base("Insufficient funds") { }
    public InsufficientFundsException(string message) : base(message) { }
    public InsufficientFundsException(string message, Exception? innerException) : base(message, inner) { }
}
CAB201 - Programming Principles
School of Computer Science, Faculty of Science