Python - Exceptions

07-Jan-2024

Understand the concept of exceptions in Python. Learn how to handle errors gracefully, use try and except blocks, and effectively manage unexpected situations in your Python programs.

Introduction

Events that take place while a program is being executed and interfere with the regular flow of instructions are called exceptions. Python offers a strong exception-handling system to deal with these circumstances. The key ideas and methods for managing exceptions in Python are covered in this documentation.


1. Try-Except Block

The basic structure for handling exceptions is the try-except block. Code inside the try block is executed, and if an exception occurs, it's caught by the corresponding except block.


# Example : Try-Except Block
# The 'try' block contains code that may raise an exception
try:
# Code that may raise an exception
result = 10 / 0

# The 'except' block handles a specific exception (ZeroDivisionError)
except ZeroDivisionError as e:
# Handle the specific exception
print(f"Error: {e}. Cannot divide by zero.")
# The program continues to execute after handling the exception print("Program continues...")

2. Multiple Except Blocks

You can have multiple except blocks to handle different types of exceptions.


# Example: Multiple Except Blocks
# The 'try' block contains code that may raise different exceptions

try:
# Code that may raise exceptions
result = int("abc")
# The 'except' blocks handle specific exceptions
except ValueError as ve:
# Handle the ValueError exception
print(f"ValueError: {ve}. Cannot convert 'abc' to an integer.")
except TypeError as te:
# Handle the TypeError exception
print(f"TypeError: {te}. Check the type conversion.")


# The program continues to execute after handling exceptions
print("Program continues...")

3. Finally Block

The finally block contains code that will be executed whether an exception occurs or not.


# Example: Finally Block

try:
# Code that may raise exceptions
result = 10 / 0
except ZeroDivisionError as zde:
# Handle the ZeroDivisionError exception print(f"ZeroDivisionError: {zde}. Cannot divide by zero.") finally:
# Code in the 'finally' block will execute regardless of exceptions
print("Finally block executed, cleaning up resources...")

4. Custom Exceptions

You can create custom exceptions by defining a new class that inherits from the Exception class.


# Example: Custom Exception
class CustomError(Exception):
# Custom exception class inherits from the base Exception class
pass
def raise_custom_exception():
# Function that raises our custom exception
raise CustomError("This is a custom exception.")
try:
# Try block where the custom exception may be raised
raise_custom_exception()

except CustomError as ce:
# Handling the custom exception print(f"CustomError: {ce}")


5. Exception Hierarchy

Python has a hierarchy of exceptions. Broad exceptions should be caught after more specific ones.



# Example: Exception Hierarchy

try:
result = int("not a number")

except ValueError :
print("Value Error : Invalid Conversion")
except Exception as e: # Catching the base Exception class to handle any exception
print(f"Caught exception: {e}")


Conclusion


Writing reliable and error-tolerant Python programs requires an understanding of exceptions and how to handle them. Important information on using finally blocks, multiple except blocks, try-except blocks, custom exceptions, and managing the exception hierarchy is provided in this documentation.

Comments