How can I handle multiple exceptions in a Python try-except block?

91 views

How can I handle multiple exceptions in a Python try-except block?

How can I handle multiple exceptions in a Python try-except block?

solveurit24@gmail.com Changed status to publish February 13, 2025
0

You can handle multiple exceptions by specifying multiple except blocks or catching a tuple of exceptions. Here’s an example:

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except TypeError:
    print("Type error occurred!")
except:
    print("An exception occurred!")

Explanation:

  • Each except block handles a specific exception.
  • The last except block (without a specific exception) is a general fallback.
solveurit24@gmail.com Changed status to publish February 13, 2025
0