# Raising & Custom Exceptions — Python

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

> Signal errors on purpose, and define your own exception types.

## 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)
```
