Sometimes a single block of code can produce different types of errors.
Python allows you to handle multiple exceptions in different ways.
Handling multiple exceptions makes your program more professional and stable.
1. USING MULTIPLE EXCEPT BLOCKS
You can handle each error separately.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
Each except block handles a specific error type.
2. HANDLING MULTIPLE EXCEPTIONS IN ONE BLOCK
You can handle multiple exceptions together using parentheses.
try:
num = int(input("Enter a number: "))
result = 10 / num
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero occurred.")
This is useful when you want the same message for different errors.
3. USING GENERIC EXCEPTION (AS e)
If you want to catch all types of errors:
try:
num = int("abc")
except Exception as e:
print("Error:", e)
Exception is the base class for most errors.e stores the actual error message.
4. ORDER OF EXCEPT BLOCKS
Always write specific exceptions first, and generic exceptions last.
Correct order:
try:
num = int(input("Enter number: "))
result = 10 / num
except ValueError:
print("Invalid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print("Other error:", e)
If Exception is written first, specific errors will never execute.
WHY HANDLE MULTIPLE EXCEPTIONS?
• Different errors need different solutions
• Makes debugging easier
• Improves user experience
• Prevents unexpected crashes
KEY POINTS
• Use multiple except blocks for different error types
• Use (Error1, Error2) to combine errors
• Use Exception as e for general handling
• Always place general exception at the end
Handling multiple exceptions is an important step toward writing robust and professional Python programs.