0% found this document useful (0 votes)
3 views

Exception Handling

Uploaded by

SACHIN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Exception Handling

Uploaded by

SACHIN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Exception handling in Python is a way to manage errors that occur during the execution of a

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:

### Basic Structure

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

Let’s look at a simple example where we handle a division by zero error:

```python

Try:

Numerator = 10

Denominator = 0

Result = numerator / denominator

Print(result)

Except ZeroDivisionError:

Print(“Error: Denominator cannot be 0.”)

```

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:

Print(“Error: Denominator cannot be 0.”)

Except IndexError:

Print(“Error: Index out of bound.”)

```

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.

### Using `else` and `finally`

You can also use `else` and `finally` blocks with `try...except`:

- The `else` block runs if no exceptions are raised.

- The `finally` block runs no matter what, even if an exception occurs.

```python
Try:

Num = int(input(“Enter a number: “))

Assert num % 2 == 0

Except:

Print(“Not an even number!”)

Else:

Reciprocal = 1 / num

Print(f”The reciprocal is {reciprocal}”)

Finally:

Print(“This block always executes.”)

```

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.

You might also like