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:
- We define a
divide_numbers
function that takes two argumentsx
andy
. - Inside the function, we use a
try
block to attempt the division ofx
byy
. - 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 ofx
ory
are incompatible for division.- The generic
Exception
block is used to catch any unexpected exceptions.
- If no exceptions are raised within the
try
block, the code in theelse
block is executed, which displays the result of the division. - 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).
- Successful division (should execute the
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′]