แบบฝึกหัด C#

Custom Domain Exception

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

How it works

Create and catch an exception that expresses a business failure.

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); }
    }
}
Expected output
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.