0% found this document useful (0 votes)
7 views10 pages

Exception Handling in Python Part3

The document provides a comprehensive overview of exception handling in Python, detailing the use of try-except blocks, including multiple except clauses, and the optional else and finally blocks. It explains how to handle specific exceptions, utilize generic exception handling, and the importance of raising exceptions explicitly. Key points emphasize the structure and readability of code when managing errors effectively.

Uploaded by

Amandeep kaur
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)
7 views10 pages

Exception Handling in Python Part3

The document provides a comprehensive overview of exception handling in Python, detailing the use of try-except blocks, including multiple except clauses, and the optional else and finally blocks. It explains how to handle specific exceptions, utilize generic exception handling, and the importance of raising exceptions explicitly. Key points emphasize the structure and readability of code when managing errors effectively.

Uploaded by

Amandeep kaur
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

try:

# Code that may raise an exception


result = 10 / 0
except ZeroDivisionError:
# Code to handle the exception
print("Cannot divide by zero")

Basic exception handling provides a foundational mechanism for responding to


errors and preventing the abrupt termination of a program. It is often expanded
upon with additional features like else and finally blocks for more
comprehensive error management.

5. try-except block:
The try and except blocks in Python form the core of exception handling.
These blocks allow you to write code that gracefully manages and responds to
potential errors during the execution of a program.

Basic Syntax:
try:
# Code that may raise an exception
# ...
except ExceptionType as e:
# Code to handle the exception
# ...
Key Components:

1. try Block:
- The try block contains the code that might raise an exception. If an exception
occurs within this block, the control is transferred to the corresponding except
block.
2. except Block:
- The except block contains the code to handle the exception. It specifies the
type of exception (or multiple types) that it can catch. If an exception of the
specified type occurs in the try block, the code in the corresponding except
block is executed.

Example:

python
try:
# Code that may raise an exception
result = 10 / 0 # Division by zero
except ZeroDivisionError as e:
# Code to handle the exception
print(f"Exception: {e}")

In this example, the try block attempts to perform a division by zero, which
raises a ZeroDivisionError. The corresponding except block catches this specific
exception type and executes the code inside, printing a custom message.

Multiple except Blocks:


In Python, you can handle multiple types of exceptions in the same try-
except block by including multiple except clauses. Each except clause specifies
a particular type of exception that it can handle. This allows you to provide
specific handling for different types of errors that may occur in the try block.
Syntax:
try:
# Code that may raise exceptions
# ...
except ZeroDivisionError as e:
# Code to handle ZeroDivisionError
# ...
except ValueError as e:
# Code to handle ValueError
# ...
Example:
try:
# Code that may raise exceptions
value = int(input("Enter a number: "))
result = 10 / value
index = [1, 2, 3]
print(index[value])
except ZeroDivisionError as e:
print(f"Error: {e}. Cannot divide by zero.")
except IndexError as e:
print(f"Error: {e}. Index out of range.")
except ValueError as e:
print(f"Error: {e}. Please enter a valid number.")
except Exception as e:
print(f"Unexpected Error: {e}")

This allows you to handle different types of exceptions in a more specific


manner.
Using a Generic Exception:

In Python, you can use a more generic except block to catch exceptions of the
base Exception class. While it is generally recommended to handle specific
exceptions whenever possible, using a generic except block allows you to catch
any exception that inherits from the Exception class.
Syntax:
try:
# Code that may raise an exception
# ...
except Exception as e:
# Code to handle any exception
# ...
Example:
try:
value = int(input("Enter a numerator: "))
divisor = int(input("Enter a divisor: "))

result = value / divisor


print(f"Result: {result}")

except Exception as e:
print(f"Error: {e}")

# Code continues here, without a finally block


print("Program continues...")
Notes:
• Using a generic except Exception as ‘e’ block catches any exception,
including built-in and user-defined exceptions.
• While it provides a catch-all mechanism, it might make debugging more
challenging since you lose specificity about the type of exception that
occurred.
• It is generally considered good practice to use specific except blocks
whenever possible, as this allows for more precise error handling.
• While catching any exception with Exception is possible, it may make
debugging more challenging, as it includes a wide range of exceptions.

The try-except block provides a foundational mechanism for dealing with


exceptions, allowing you to control the flow of your program even when errors
occur.

Utilizing a generic except block can be beneficial when you aim to offer a
fallback or default behavior for unexpected exceptions.

6. try-except else block:


In Python, the `try`, `except`, and `else` blocks can be combined to
provide a more structured way to handle exceptions. The `else` block is
executed only if no exceptions are raised in the `try` block. This allows you to
separate the code that may raise an exception from the code that should run only
when no exceptions occur.

Syntax:
try:
# Code that may raise an exception
# ...
except ExceptionType as e:
# Code to handle the exception
# ...
else:
# Code to execute if no exception is raised
# ...

Example:
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError as e:
print(f"Error: Invalid input ({e})")
except ZeroDivisionError as e:
print(f"Error: Division by zero ({e})")
else:
print(f"Result: {result}")
```

In this example:

1. The `try` block attempts to get user input and perform a division.
2. If the user enters an invalid number (raises `ValueError`) or attempts to divide
by zero (raises `ZeroDivisionError`), the corresponding `except` block is
executed.
3. If no exception is raised in the `try` block, the `else` block is executed, and it
prints the result of the division.
Key Points:
• The `else` block is optional and comes after all `except` blocks.
• The code in the `else` block is executed only if no exceptions are raised in
the `try` block.
• It helps in separating the code that may raise exceptions from the code
that should run when everything goes smoothly.

When to Use `else` with `try-except`:

• Use `else` when you want to perform actions that should only happen
when no exceptions occur.
• It improves code readability by making it clear which part of the code is
responsible for handling exceptions and which part is executed when no
exceptions are raised.
try:
# Code that may raise an exception
# ...
except ExceptionType as e:
# Code to handle the exception
# ...
else:
# Code to execute if no exception is raised
# ...

Adding the `else` block makes the structure more intuitive and can make the
code more readable by avoiding unnecessary indentation of the success case.
7. try except else finally:

In Python, the `try`, `except`, `else`, and `finally` blocks can be combined to
create a comprehensive exception-handling structure. Each block serves a
distinct purpose:

• `try`: Contains the code that may raise an exception.


• `except`: Contains the code to handle specific exceptions.
• `else`: Contains the code that should run only if no exceptions are raised.
• `finally`: Contains code that always executes, regardless of whether an
exception occurred.

Syntax:
try:
# Code that may raise an exception
# ...
except ExceptionType as e:
# Code to handle the exception
# ...
else:
# Code to execute if no exception is raised
# ...
finally:
# Code to execute regardless of exceptions
# ...
Example:
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError as e:
print(f"Error: Invalid input ({e})")
except ZeroDivisionError as e:
print(f"Error: Division by zero ({e})")
else:
print(f"Result: {result}")
finally:
print("This code always executes, regardless of exceptions.")

In this example:
1. The `try` block attempts to get user input and perform a division.
2. If the user enters an invalid number (raises `ValueError`) or attempts to divide
by zero (raises `ZeroDivisionError`), the corresponding `except` block is
executed.
3. If no exception is raised in the `try` block, the `else` block is executed,
printing the result of the division.
4. The `finally` block contains code that always executes, regardless of whether
an exception occurred or not. It is commonly used for cleanup operations.

Key Points:
• The `else` block is optional and comes after all `except` blocks. It
executes only if no exceptions are raised.
• The `finally` block is optional and comes after the `else` block. It
executes regardless of whether an exception occurred or not.
• The `else` and `finally` blocks are often used together when you want to
perform specific actions regardless of whether an exception occurred.
Using `try`, `except`, `else`, and `finally` together provides a comprehensive
structure for handling exceptions, ensuring that your code can gracefully
manage errors and execute cleanup operations as needed.

8. raise:

In Python, the `raise` statement is used to explicitly raise an exception. This


allows you to interrupt the normal flow of the program and indicate that an
exceptional situation has occurred. You can raise a specific exception or create
your own custom exception.

Syntax:

raise ExceptionType("Optional custom message")

7.1 Raising a Built-in Exception:

try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative")
except ValueError as e:
print(f"Error: {e}")

In this example, if the user enters a negative age, a `ValueError` is raised with a
custom error message.

You might also like