C# Practice Exercises

Custom Domain Exception

Create and catch an exception that expresses a business failure.

Introduction

A named exception communicates intent more clearly than a generic Exception.

The custom type retains normal exception behavior while making the catch clause precise.

Runnable C# example

C#
Run code →
Program.cs
using System;
class InsufficientStockException(string message) : Exception(message) { }
class Program
{
    static void Reserve(int available, int requested)
    {
        if (requested > available) throw new InsufficientStockException("Not enough stock");
    }
    static void Main()
    {
        try { Reserve(2, 3); }
        catch (InsufficientStockException error) { Console.WriteLine(error.Message); }
    }
}
Result of running the code
Not enough stock

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges