Tutorials / C# for Beginners / Exceptions: try, catch, finally and throw

Exceptions: try, catch, finally and throw

13 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. Expense tracker, part 2: the menu and summaries

When things go wrong at runtime

The compiler catches typing mistakes. It cannot catch a missing file, a network failure or a user who types "abc" where a number is needed. Those problems happen while the program runs. In C# they are reported as exceptions. If nobody handles an exception, the program stops and prints a stack trace.

try, catch, finally

Put the risky code in a try block. Follow it with one or more catch blocks for the problems you can deal with. A finally block runs whatever happens, which is the place for cleanup.

Console.Write("Enter a number to divide 100 by: ");
string? text = Console.ReadLine();

try
{
    int divisor = int.Parse(text!);
    int result = 100 / divisor;
    Console.WriteLine($"100 / {divisor} = {result}");
}
catch (FormatException)
{
    Console.WriteLine("That was not a whole number.");
}
catch (DivideByZeroException)
{
    Console.WriteLine("You cannot divide by zero.");
}
catch (OverflowException)
{
    Console.WriteLine("That number is too large.");
}
finally
{
    Console.WriteLine("Calculation finished.");
}

// Throwing our own exception
try
{
    Withdraw(balance: 500m, amount: 800m);
}
catch (InsufficientFundsException ex)
{
    Console.WriteLine($"{ex.Message} Short by {ex.Shortfall:N2}.");
}

static decimal Withdraw(decimal balance, decimal amount)
{
    if (amount <= 0)
    {
        throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive.");
    }
    if (amount > balance)
    {
        throw new InsufficientFundsException(amount - balance);
    }
    return balance - amount;
}

class InsufficientFundsException : Exception
{
    public decimal Shortfall { get; }

    public InsufficientFundsException(decimal shortfall)
        : base("Not enough money in the account.")
    {
        Shortfall = shortfall;
    }
}

Walking through it

Three different things can go wrong in the first block. int.Parse can throw FormatException if the text is not a number, and OverflowException if it is too large for an int. The division can throw DivideByZeroException. Each has its own catch, with its own helpful message. C# runs the first matching catch only.

The exclamation mark in text! silences the null warning, since a null here would throw an ArgumentNullException that nobody catches. In a real program, check for null first.

The finally block prints its message in every case: success, handled error or unhandled error. Typical uses are closing files and releasing connections. You will often see using statements used for this instead, as in the next lesson.

Next, Withdraw uses throw to signal bad input or an impossible request. I used the built-in ArgumentOutOfRangeException for the first and a custom InsufficientFundsException for the second. A custom exception class inherits from Exception and can carry extra data. Here it carries the shortfall, so the caller can show it.

Rules I follow

  • Catch only what you can handle. If you cannot recover, let it travel up to a place that can.
  • Catch specific types first. A catch for Exception catches everything, so it goes last, if at all.
  • Never write an empty catch block. Swallowing errors hides bugs for months.
  • Use throw; to rethrow, not throw ex;. The first keeps the original stack trace. The second resets it.
  • Do not use exceptions for normal flow. If bad input is expected, use TryParse. Exceptions are slow compared to a simple check, and they make the code harder to follow.

Reading a stack trace

When a program crashes, read the stack trace from the top. The first line names the exception and message. The next lines show which methods were running, newest first. Find the first line that points to your own file and line number. That is where to look.

Common mistakes

  • Catching Exception everywhere and printing "something went wrong".
  • Losing the original error when wrapping. Pass it as the inner exception: throw new MyException("text", ex);.
  • Putting too much in the try block. Keep it small so you know which line failed.

Try it yourself

  1. Write a program that asks for two numbers and divides them, handling all three problems from the example without crashing.
  2. Rewrite it using TryParse and an if for zero. Which version is shorter?
  3. Create a InvalidAgeException and throw it from a method that sets a person's age when it is outside 0 to 130.
csharp
Console.Write("Enter a number to divide 100 by: ");
string? text = Console.ReadLine();

try
{
    int divisor = int.Parse(text!);
    int result = 100 / divisor;
    Console.WriteLine($"100 / {divisor} = {result}");
}
catch (FormatException)
{
    Console.WriteLine("That was not a whole number.");
}
catch (DivideByZeroException)
{
    Console.WriteLine("You cannot divide by zero.");
}
catch (OverflowException)
{
    Console.WriteLine("That number is too large.");
}
finally
{
    Console.WriteLine("Calculation finished.");
}

// Throwing our own exception
try
{
    Withdraw(balance: 500m, amount: 800m);
}
catch (InsufficientFundsException ex)
{
    Console.WriteLine($"{ex.Message} Short by {ex.Shortfall:N2}.");
}

static decimal Withdraw(decimal balance, decimal amount)
{
    if (amount <= 0)
    {
        throw new ArgumentOutOfRangeException(nameof(amount), "Amount must be positive.");
    }
    if (amount > balance)
    {
        throw new InsufficientFundsException(amount - balance);
    }
    return balance - amount;
}

class InsufficientFundsException : Exception
{
    public decimal Shortfall { get; }

    public InsufficientFundsException(decimal shortfall)
        : base("Not enough money in the account.")
    {
        Shortfall = shortfall;
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account