> ## 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.

# Flatten Nested Try

#### Sourcery refactoring id: `flatten-nested-try`

#### Description:

Merge nested try-statement into a single try

#### Before:

```python
def testConnection(db, credentials):
    try:
        try:
            db.connect(credentials)
        except InvalidCredentials:
            return "Check your credentials"
        except ConnectionError:
            return "Error while trying to connect"
    finally:
        print("Connection attempt finished")
    return "Connection Successful"
```

#### After:

```python
def testConnection(db, credentials):
    try:
        db.connect(credentials)
    except InvalidCredentials:
        return "Check your credentials"
    except ConnectionError:
        return "Error while trying to connect"
    finally:
        print("Connection attempt finished")
    return "Connection Successful"
```

#### Explanation:

Flattening try-except statements nested within a try-finally generates
equivalent code that is easier to read and expand upon.
