You can use if
, else
, and try
/except
together with conditions in Python to handle exceptions based on specific conditions. Here’s an example of how to do this:
try:
# Perform some operation that may raise an exception
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
# Handle the ValueError (e.g., if the user enters a non-integer)
print("Error: Invalid input. Please enter an integer.")
except ZeroDivisionError:
# Handle the ZeroDivisionError (e.g., if the user enters 0)
print("Error: Division by zero is not allowed.")
else:
# If no exception occurred, execute this block
if result > 5:
print("Result is greater than 5")
else:
print("Result is not greater than 5")
In this example:
- The
try
block attempts to perform a division operation based on user input. It can raise two types of exceptions:ValueError
(if the user enters a non-integer) andZeroDivisionError
(if the user enters 0). - The
except
blocks catch these specific exceptions and handle them with appropriate error messages. - The
else
block is executed if no exception occurs. Within theelse
block, there’s anif
condition that checks whether theresult
is greater than 5 and prints a message accordingly.
This structure allows you to conditionally handle exceptions based on specific conditions while also providing alternative behavior when no exceptions are raised.