Lesson 04
try and except Basics — Syntax for Handling Exceptions
Learn the try and except syntax — monitor risky code, catch runtime exceptions, and keep Python programs running gracefully.
Definition: Exception handling =
try(monitor) +except(respond). The goal is to replace technical crashes with messages users can understand.
What you will learn
- Understand the
tryandexceptsyntax - Learn how Python monitors risky code
- See how PVM exits a try block on error
- Build a safe division program
- Understand
else,finally, andraiseat a high level
The five exception keywords
Think of exception handling as a team where each keyword has one job.
Quick summary
| Keyword | Purpose |
|---|---|
try |
Monitor risky statements |
except |
Catch matching exceptions |
else |
Execute only when no exception occurs |
finally |
Always runs (cleanup) |
raise |
Manually create an exception |
This lesson focuses on
tryandexcept.
1. Basic syntax
Every exception handling block follows the same structure.
try:
# risky statements
a = int("10")
b = int("0")
result = a / b
except ZeroDivisionError:
print("Denominator cannot be zero")
except ValueError:
print("Please enter valid numbers")Visual structure
2. What does the try block do?
The try block is called the Exception Monitoring Block.
It tells Python:
"Watch these lines carefully. They may produce a runtime exception."
Example
try:
print("Step 1")
result = 10 / 0
print("Step 2") # never runsWhat happens internally?
Important rule
When an exception occurs:
- ✅ Current line stops immediately
- ✅ PVM exits the try block
- ❌ Remaining lines inside
tryare skipped
3. What does the except block do?
The except block is called the Exception Processing Block.
Its job is to replace this:
ZeroDivisionError: division by zerowith this:
Please don't enter zero.Visual comparison
4. Multiple except blocks
Different errors deserve different messages.
# Simulated user input — no input() in browser playground
a = int("10")
b = int("0")
try:
print(a / b)
except ValueError:
print("Enter numbers only")
except ZeroDivisionError:
print("Don't divide by zero")Try changing a = int("abc") in the playground to trigger ValueError instead.
Decision flow
Python executes only the matching except block.
5. Safe division program
This is how real applications validate user input — here with fixed values instead of input().
def safe_div(a, b):
print("Program started")
print("Trying division:", a, "/", b)
try:
result = a / b
print("Division OK:", result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid numbers")
print("Program ended")
safe_div(10, 2) # Division OK: 5.0
safe_div(10, 0) # Cannot divide by zeroChange a or b in the playground to simulate different runtime situations.
6. Step-by-step program execution
Let's trace a real execution.
print("Program started")
try:
result = 10 / 0
print(result) # skipped
except ZeroDivisionError:
print("Don't enter zero")
print("Program ended")Execution timeline
Final output
Program started
Don't enter zero
Program endedNotice that print(result) never executes.
7. What if there is NO exception?
The try block simply finishes normally.
Case 1 — Success:
try:
print(10 / 2)
except ZeroDivisionError:
print("Error")Output: 5.0
Case 2 — Failure:
try:
print(10 / 0)
except ZeroDivisionError:
print("Error")Output: Error
8. Common beginner mistakes
Mistake 1 — try without except:
try:
print(10 / 2)
# ❌ Invalid syntax — need at least one except or finallyMistake 2 — Wrong exception type:
try:
int("abc")
except KeyError:
print("Handled") # ❌ ValueError is raised, not KeyErrorCorrect approach:
try:
int("abc")
except ValueError:
print("Please enter numbers") # ✅ Match the class exactlyMemory map
Interview questions
Q1. What is the purpose of a try block?
Answer: To monitor statements that may raise runtime exceptions.
Q2. What happens when an exception occurs inside try?
Answer: PVM immediately exits the try block, skips the remaining statements, and searches for a matching except.
Q3. Can one try have multiple except blocks?
Answer: Yes. Each except handles a different exception class with its own user-friendly message.
Key takeaways
try= Exception Monitoring Blockexcept= Exception Processing Block- When an exception occurs, PVM exits the try block immediately
- Multiple
exceptblocks allow different messages for different errors - Exception handling makes applications robust by preventing crashes
- Next:
elseandfinallyBlocks — whenelseruns, whyfinallyalways executes, and resource cleanup patterns
Loading playground…
Check your understanding
try except basics quiz
try block is called:
1 / 10