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:

  1. 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) and ZeroDivisionError (if the user enters 0).
  2. The except blocks catch these specific exceptions and handle them with appropriate error messages.
  3. The else block is executed if no exception occurs. Within the else block, there’s an if condition that checks whether the result 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.

By DSD