Error handling, also known as exception handling, is a crucial aspect of writing robust and reliable code. Exceptions are events that occur during the execution of a program that disrupts the normal flow of instructions. Python provides a mechanism to handle exceptions using try-except blocks, allowing us to gracefully handle errors and prevent program crashes.

Let’s explore error handling in Python:

# Handling exceptions using try-except blocks
try:
    # Code that may raise an exception
    x = 10 / 0
except ZeroDivisionError:
    # Code to handle the specific exception
    print("Error: Division by zero occurred.")

# Handling multiple exceptions
try:
    # Code that may raise an exception
    y = int("abc")
except ZeroDivisionError:
    # Code to handle ZeroDivisionError
    print("Error: Division by zero occurred.")
except ValueError:
    # Code to handle ValueError
    print("Error: Invalid conversion to int.")

# Handling any exception
try:
    # Code that may raise an exception
    z = int("10") / 0
except Exception as e:
    # Code to handle any exception
    print("An error occurred:", str(e))

# Handling exceptions with an else block
try:
    # Code that may raise an exception
    result = 10 / 5
except ZeroDivisionError:
    # Code to handle ZeroDivisionError
    print("Error: Division by zero occurred.")
else:
    # Code to execute if no exception occurred
    print("Result:", result)

# Handling exceptions with a finally block
try:
    # Code that may raise an exception
    x = 10 / 0
except ZeroDivisionError:
    # Code to handle ZeroDivisionError
    print("Error: Division by zero occurred.")
finally:
    # Code to execute regardless of whether an exception occurred
    print("Finally block executed.")

Explanation:

  • We can handle exceptions using try-except blocks. The code that may raise an exception is placed within the try block, and the code to handle the exception is placed within the except block.
  • We can handle multiple exceptions by adding multiple except blocks, each handling a specific exception.
  • We can use the Exception base class to handle any exception.
  • The else block is executed if no exception occurred within the try block.
  • The finally block is executed regardless of whether an exception occurred. It is commonly used to perform cleanup operations.
  • The as keyword is used to assign the exception object to a variable, allowing us to access information about the exception.

Now it’s time for a practical task:

Task 17:

Write a function called divide_numbers() that takes two numbers as input and performs division. Handle the ZeroDivisionError by displaying an error message if the second number is zero. Test the function with different inputs, including division by zero.

Once you’ve completed the task, you can proceed to the next lesson.