> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Merge Exception Handlers

#### Sourcery refactoring id: `merge-except-handler`

#### Description

Merge exception handlers with the same body into a single except handler.

#### Before

```python
try:
    f = open("myfile.txt")
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    logger.exception("Error while reading myfile.txt")
    raise
except ValueError as err:
    logger.exception("Error while reading myfile.txt")
    raise
```

#### After

```python
try:
    f = open("myfile.txt")
    s = f.readline()
    i = int(s.strip())
except (OSError, ValueError) as err:
    logger.exception("Error while reading myfile.txt")
    raise
```

#### Explanation

By merging except handlers with the same body we remove duplicate code. This
makes it easier to read, and when changing the logic we won't accidentally
change it in only one place instead of both.

#### Related Rules

- [remove-redundant-except-handler](/reference/refactorings/python/remove-redundant-except-handler/) to
  remove unreachable `except` blocks
- [remove-redundant-exception](/reference/refactorings/python/remove-redundant-exception/) to clean up the
  tuple of an except clause
- [use-contextlib-suppress](/reference/refactorings/python/use-contextlib-suppress/) instead of empty
  `except` blocks
- [do-not-use-bare-except](/reference/refactorings/python/do-not-use-bare-except/) to always specify which
  errors an `except` block is handling
