Python Learning Series · @onlysamarrr · Day 24 / 30

Day 24: try/except

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

Quick Answer

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.

What You Will Learn

Code

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")

Output

Invalid input: invalid literal for int() with base 10: 'abc'
Hamesha chalega
Cannot divide by zero

Code Explained, Line by Line

  1. The try block holds code that might raise an error.
  2. except ValueError as e catches only ValueError, and e holds the error message.
  3. else runs only when the try block finished without an error.
  4. finally runs whether an error happened or not, which is ideal for cleanup.
  5. ZeroDivisionError is raised when dividing by zero, and it can be caught separately.
Common Mistake: Never write a bare except: or except Exception: pass. It hides bugs and you will not know where the error came from.

Real-Life Use

Forms, file reading and network calls use try/except so one bad input does not crash the app.

Practice Task: Handle zero division and build a safe input that does not crash on wrong input.

Test Yourself — MCQs

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?

Today's 5 Reels (from the 90-Day Plan Excel)

116/450ConceptErrors kya hote
117/450Live demotry/except demo
118/450Common mistakeBare except mat likho
119/450QuizQuiz: zero division handle
120/450Interview / real lifeReal life: safe input
← Day 23Day 25 →