Exception Handling with try/except
Sometimes, programs crash because of unexpected errors — like dividing by zero or accessing a file that doesn’t exist.
Instead of crashing, we can use exception handling to deal with those errors gracefully.
Python provides four key tools:
try
except
else
finally
1. try and except
Wrap risky code in a try
block. If an error happens, Python jumps to the except
block.
try: result = 10 / 0 except ZeroDivisionError: print("Oops! You can't divide by zero.")
Explanation:
- The division causes an error.
- Python skips the crash and shows a message instead.
2. Handling Multiple Error Types
You can catch different types of exceptions in separate except
blocks.
try: num = int("abc") except ValueError: print("That’s not a valid number.") except TypeError: print("Type mismatch.")
Explanation:
- This handles a
ValueError
caused byint("abc")
.
3. else and finally
else
runs only if no error occurs.finally
runs no matter what, even if there’s an error.
try: value = int("42") except ValueError: print("Conversion failed.") else: print("Conversion succeeded:", value) finally: print("Done checking.")
Explanation:
else
confirms success.finally
is good for cleanup (like closing files or connections).
Summary
Keyword | Purpose |
---|---|
try | Run risky code |
except | Handle specific errors |
else | Runs if no exception occurred |
finally | Always runs — useful for cleanup |
What’s Next?
In the next lesson, we’ll learn how to read and write files to store and retrieve data.
Quiz
0 / 1
In Python, the 'finally' block in a try/except structure is only executed if an exception is thrown and caught.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result