---
title: Do Not Throw Generic Errors
impact: HIGH
impactDescription: enables proper error handling and monitoring
tags: error-handling, exceptions, custom-errors, debugging, quality, csharp
---

## Do Not Throw Generic Errors

Throwing specific exceptions allows callers to handle specific error cases.

**Incorrect (generic exception):**

```csharp
if (user == null)
{
    throw new Exception("User not found"); // Generic
}
```

**Correct (specific exception):**

```csharp
if (user == null)
{
    throw new KeyNotFoundException($"User {id} not found"); // Built-in specific
}

// Or custom exception
public class UserNotFoundException : Exception { ... }

if (user == null)
{
    throw new UserNotFoundException(id);
}
```

**Tools:** Roslyn Analyzers (CA2201), SonarQube
