> For the complete documentation index, see [llms.txt](https://ricardomol.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ricardomol.gitbook.io/notes/backend/python/exceptions.md).

# Exceptions

## Exceptions

&#x20;**The code which can cause an exception to occur is put in the `try` block and the handling of the exception is implemented in the `except`block**.

Example:

```python
try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
```

## Handling multiple exceptions

**Three methods to handle multiple exceptions:**

### 1. Putting **all the exceptions in a tuple**

```python
try:
    file = open('test.txt', 'rb')
except (IOError, EOFError) as e:
    print("An error occurred. {}".format(e.args[-1]))
```

### 2. Separate `except` blocks

We can have as many `except` blocks as we want.

Example:

```python
try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occurred.")
    raise e
except IOError as e:
    print("An error occurred.")
    raise e
```

If the exception is not handled by the first `except` block then it may be handled by a following block, or none at all.

### 3. Trapping ALL exceptions:

```python
try:
    file = open('test.txt', 'rb')
except Exception as e:
    # Some logging if you want
    raise e
```

Helpful when you have no idea about the exceptions which may be thrown by your program.

## `finally` clause

**The code wrapped in the`finally` clause will run whether or not an exception occurred.**

Example: to perform clean-up after a script:

```python
try:
    file = open('test.txt', 'rb')
except IOError as e:
    print('An IOError occurred. {}'.format(e.args[-1]))
finally:
    print("This would be printed whether or not an exception occurred!")

# Output: An IOError occurred. No such file or directory
# This would be printed whether or not an exception occurred!
```

## `try/else` clause

We might want some **code to run if no exception occurs**.&#x20;

It would run **before the finally clause**.

Example:

```python
try:
    print('I am sure no exception is going to occur!')
except Exception:
    print('exception')
else:
    # any code that should only run if no exception occurs in the try,
    # but for which exceptions should NOT be caught
    print('This would only run if no exception occurs. And an error here '
          'would NOT be caught.')
finally:
    print('This would be printed in every case.')

# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs. And an error here would NOT be caught
# This would be printed in every case.
```
