# Raising & Custom Exceptions — Python Fundamentals: From Basics to Async

Source: https://www.skillbyai.com/en/python/py-raising-custom-exceptions

> Raise exceptions to reject bad input early, and define custom exception classes for your domain.

## raise

`raise` triggers an exception manually — useful for rejecting invalid input as early as possible.

```python
def set_age(age):
    if age < 0:
        raise ValueError("age can't be negative")
    return age

set_age(-5)   # raises ValueError: age can't be negative
```

## Custom exception class

Subclass `Exception` to create a domain-specific error your code — and callers — can catch by name.

```python
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("not enough balance")
    return balance - amount

try:
    withdraw(100, 500)
except InsufficientFundsError as e:
    print("Blocked:", e)
```
