---
title: Do Not Throw Generic Exceptions
impact: HIGH
impactDescription: enables specific error handling and accurate monitoring
tags: error-handling, exceptions, custom-errors, debugging, quality, kotlin
---

## Do Not Throw Generic Exceptions

Generic exceptions like `Exception`, `RuntimeException`, or `Throwable` lack specific context. They make it impossible for callers to catch specific error types and handle them appropriately (e.g., retrying a network error but failing on a validation error).

**Incorrect (generic exceptions):**

```kotlin
if (user == null) {
    throw Exception("error")
}

if (!isValid) {
    throw RuntimeException("Invalid")
}
```

**Correct (specific custom exceptions):**

```kotlin
if (user == null) {
    throw UserNotFoundException("User with ID $userId not found in database")
}

if (!isValid) {
    throw ValidationException(
        field = "email",
        message = "Email format is invalid",
        value = email,
        code = "INVALID_EMAIL_FORMAT"
    )
}
```

**Custom exceptions should include:**
- Descriptive message with runtime context.
- Domain-specific naming (e.g., `InsufficientFundsException`).
- Optional error codes or structured data for debugging/API responses.

**Tools:** detekt (TooGenericExceptionThrown), Android Studio Linter, Manual Review
