π§© 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! π