---
title: Use Custom Error Classes
impact: MEDIUM
impactDescription: improves error handling granularity
tags: error-handling, exceptions, design, quality, csharp
---

## Use Custom Error Classes

Use specific, typed exceptions instead of generic `Exception`.

**Incorrect (throwing generic):**

```csharp
throw new Exception("Validation failed");
```

**Correct (custom business exceptions):**

```csharp
public class InsufficientFundsException : Exception
{
    public decimal Available { get; }
    public decimal Required { get; }

    public InsufficientFundsException(decimal available, decimal required)
        : base($"Insufficient funds. Required: {required}, Available: {available}")
    {
        Available = available;
        Required = required;
    }
}

// Usage
throw new InsufficientFundsException(100, 200);
```

**Tools:** Roslyn Analyzers
