Skip to content
Codewilds

Lesson 31 of 34 · LINQ & Errors

C# Exceptions: try, catch, finally and Custom Exceptions

medium20 XP2 min read

Things go wrong: a file is missing, a user types abc where a number belongs, a hero tries to buy a sword they cannot afford. C# reports such problems with exceptions — objects that describe the error and travel up the call stack until some code catches them. If nobody does, the program crashes with the message you have seen in earlier lessons.

try and catch

try
{
    int level = int.Parse("forty");
    Console.WriteLine(level);
}
catch (FormatException ex)
{
    Console.WriteLine($"Not a number: {ex.Message}");
}

When a statement inside try throws, the rest of the try block is skipped and the first matching catch runs. Catch specific exception types: a bare catch (Exception) also swallows bugs you would rather see. You can stack several catch blocks — the most specific first — and add a condition with when:

catch (ArgumentException ex) when (ex.ParamName == "price") { /* ... */ }

finally

A finally block runs whether or not an exception happened — perfect for cleanup:

try
{
    Console.WriteLine("Opening the vault");
    throw new InvalidOperationException("The lock is jammed");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    Console.WriteLine("Closing the vault");   // always runs
}

Throwing exceptions

Your own methods should throw when they are called with arguments that make no sense:

public static double Divide(double a, double b)
{
    if (b == 0)
    {
        throw new ArgumentException("Cannot divide by zero.", nameof(b));
    }
    return a / b;
}

Pick a fitting built-in type: ArgumentException (bad argument), ArgumentOutOfRangeException (value outside the allowed range), ArgumentNullException, InvalidOperationException (the object is not in a state that allows the call), KeyNotFoundException, NotImplementedException.

Inside a catch, throw; rethrows the same exception without losing its stack trace.

Custom exceptions

When callers need to react to a specific problem, define your own exception type by inheriting from Exception:

public class QuestLockedException : Exception
{
    public int RequiredLevel { get; }

    public QuestLockedException(int requiredLevel)
        : base($"This quest requires level {requiredLevel}.")
    {
        RequiredLevel = requiredLevel;
    }
}

Name custom exceptions with the Exception suffix, pass a helpful message to base(...), and add properties for the details callers need.

Exceptions are for exceptional cases

Throwing is slow and makes control flow harder to follow. When failure is an expected outcome — like a user typing bad input — prefer the Try pattern you met in Chapter 2: int.TryParse returns false instead of throwing.

Common mistakes

  • Empty catch blocks (catch { }) hide real bugs.
  • Catching Exception first: later, more specific catch blocks can never run (the compiler reports an error).
  • Using exceptions for normal flow — validate with if or TryParse when failure is common.

Assignment

  1. Complete InsufficientGoldException: it stores how much gold is Missing and its message is "Not enough gold: missing 20".
  2. Shop.Buy(gold, price) returns the gold left after buying. A negative price throws ArgumentOutOfRangeException; not enough gold throws InsufficientGoldException with the missing amount.
  3. Shop.TryBuy(gold, price) calls Buy and turns the result into a message: "Bought! 30 gold left", "Missing 20 gold" or "Invalid price".
  4. Shop.ParseOrDefault(text, fallback) returns int.Parse(text), but catches FormatException and OverflowException and returns fallback instead.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Errors and exceptions in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 31 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.