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
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); }
}
}
Not enough stockPractice 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.
- First Invalid Age Validate typed ages and report where the first bad entry is instead of letting the program crash. Easy
- Sum the Valid Numbers Add up the entries that are whole numbers and skip everything else, the way try/except handles bad input. Easy