🧩 Python Multiple Except Blocks β€” Handling Different Errors Separately

Introduction 🌟

Python allows you to write multiple except blocks to catch and handle different types of errors individually. This makes your code more robust, readable, and precise.

Note

πŸ’‘ Each except block handles a specific exception type.

1. Basic Example of Multiple Except Blocks 🧱

multiple_except_basic.py

try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("❌ You must enter a valid integer!")
except ZeroDivisionError:
    print("❌ Cannot divide by zero!")

βœ” If user enters a string β†’ ValueError
βœ” If user enters 0 β†’ ZeroDivisionError

2. Multiple Except Blocks With Else & Finally 🎯

multiple_except_else_finally.py

try:
    x = int("10")
    y = 10 / x
except ValueError:
    print("❌ Value conversion error")
except ZeroDivisionError:
    print("❌ Cannot divide by zero!")
else:
    print("βœ” No errors! Result =", y)
finally:
    print("πŸŽ‰ Done executing block")

Note

βœ” else runs only when no exception occurs βœ” finally runs regardless of errors

3. Handling Many Exceptions Separately 🧠

separate_exceptions.py

try:
    data = [1, 2, 3]
    print(data[5])
except IndexError:
    print("❌ Index out of range!")
except TypeError:
    print("❌ Invalid type used!")
except ValueError:
    print("❌ Invalid value!")

βœ” Each error type triggers its own block.

4. Catching Exception Messages Using as πŸ“Ž

exception_as.py

try:
    x = int("abc")
except ValueError as e:
    print("Error occurred:", e)

5. Ordering Matters! ⚠️

Always place specific exceptions firstand general exceptions later.

ordering_exceptions.py

try:
    num = int("abc")
except ValueError:
    print("❌ Not a valid integer!")
except Exception:
    print("⚠️ A general exception occurred")

Note

❌ WRONG ORDER:

wrong_order.py

try:
    num = int("abc")
except Exception:
    print("This catches everything...")
except ValueError:
    print("This will NEVER run")

βœ” Because Exception is the parent class of ValueError.

6. Real-World Example: File Handling πŸ“

file_handling_multiple.py

try:
    f = open("data.txt")
    value = int(f.read())
    result = 100 / value
except FileNotFoundError:
    print("❌ File not found!")
except ValueError:
    print("❌ File does not contain a valid number!")
except ZeroDivisionError:
    print("❌ Division by zero is not allowed!")

7. Real-World Example: User Authentication πŸ”

auth_multiple_excepts.py

try:
    users = {"admin": "123"}
    username = input("User: ")
    password = input("Pass: ")

    if username not in users:
        raise KeyError("User not found")
    if users[username] != password:
        raise PermissionError("Wrong password")

    print("βœ” Login successful!")
except KeyError as e:
    print("❌", e)
except PermissionError as e:
    print("❌", e)

8. When to Use Multiple Except Blocks? 🎯

  • βœ” When different errors require different actions
  • βœ” When debugging complex code
  • βœ” When providing user-friendly error messages
  • βœ” When recovering gracefully from multiple failure points

Conclusion πŸŽ‰

>>β€œMultiple Except Blocks make your error handling precise β€” catching only what you intend.” ✨

You now fully understand Multiple Except Blocks in Python! Want the next topic? Try Custom Exceptions, Else Block, Finally Block, or Raising Exceptions. Just tell me! 😊