Exception Handling
Exception Handling
program. It allows you to respond to different error conditions gracefully, rather than letting
the program crash. Here’s a basic overview of how it works, along with an example:
In Python, you use the `try...except` block to handle exceptions. The code that might cause an
exception is placed inside the `try` block, and the code to handle the exception is placed
inside the `except` block.
### Example
```python
Try:
Numerator = 10
Denominator = 0
Print(result)
Except ZeroDivisionError:
```
In this example:
- The code inside the `try` block attempts to divide 10 by 0, which raises a
`ZeroDivisionError`.
- The `except` block catches this specific exception and prints an error message.
### Catching Multiple Exceptions
You can also handle multiple exceptions by specifying different `except` blocks for each type
of exception:
```python
Try:
Even_numbers = [2, 4, 6, 8]
Print(even_numbers[5])
Except ZeroDivisionError:
Except IndexError:
```
Here, the code tries to access an index that doesn’t exist in the list, raising an `IndexError`.
The `except IndexError` block catches this exception and prints an appropriate message.
You can also use `else` and `finally` blocks with `try...except`:
```python
Try:
Assert num % 2 == 0
Except:
Else:
Reciprocal = 1 / num
Finally:
```
In this example:
- If the user inputs an even number, the `else` block calculates and prints the reciprocal.
- The `finally` block always executes, regardless of whether an exception was raised or not.