Python Learning Series · @onlysamarrr · Day 24 / 30
Day 24 teaches try/except error handling. Code that may fail goes in try, a specific error is caught in except, else runs only when no error happened, and finally always runs.
Phase: Intermediate · Reels: 116/450 – 120/450
Day 24 teaches try/except error handling. Code that may fail goes in try, a specific error is caught in except, else runs only when no error happened, and finally always runs.
try:
x = int("abc")
except ValueError as e:
print("Invalid input:", e)
else:
print("No error")
finally:
print("Hamesha chalega")
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
Invalid input: invalid literal for int() with base 10: 'abc' Hamesha chalega Cannot divide by zero
Forms, file reading and network calls use try/except so one bad input does not crash the app.
Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.
Q1. What does else do in try/except?
Q2. What does finally do?
Q3. Why avoid a bare except?
| 116/450 | Concept | Errors kya hote |
| 117/450 | Live demo | try/except demo |
| 118/450 | Common mistake | Bare except mat likho |
| 119/450 | Quiz | Quiz: zero division handle |
| 120/450 | Interview / real life | Real life: safe input |