Skip to content

Mastering Python Error Handling: Handling Multiple Exceptions Made Easy

def divide_numbers(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("Error: Division by zero")
    except TypeError:
        print("Error: Invalid data type for division")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
    else:
        print(f"The result of {x} / {y} is {result}")

# Test cases
divide_numbers(10, 2)  # This should execute the else block
divide_numbers(10, 0)  # This should trigger the ZeroDivisionError exception
divide_numbers("10", 2)  # This should trigger the TypeError exception
divide_numbers(10, '2')  # This should trigger the TypeError exception

In this code:

  1. We define a divide_numbers function that takes two arguments x and y.
  2. Inside the function, we use a try block to attempt the division of x by y.
  3. We use multiple except blocks to catch specific exceptions:
    • ZeroDivisionError is raised when attempting to divide by zero.
    • TypeError is raised if the data types of x or y are incompatible for division.
    • The generic Exception block is used to catch any unexpected exceptions.
  4. If no exceptions are raised within the try block, the code in the else block is executed, which displays the result of the division.
  5. We provide test cases to demonstrate different scenarios:
    • Successful division (should execute the else block).
    • Division by zero (should trigger the ZeroDivisionError exception).
    • Invalid data type (should trigger the TypeError exception).

This code showcases how to handle multiple exceptions using try, except, and the optional else block to provide specific error messages or handle successful execution.

To read more about Error Handling please read this article.

Try the questions below.

[ays_quiz id=’1′]

Leave a Reply

Your email address will not be published. Required fields are marked *