Exceptions & File Handling
Python · Beginner
Definition
Exceptions signal errors at runtime and are handled with try/except; files are read and written with open().
Robust programs handle errors gracefully and work with data files.
Diagram
Flowchart
Example: Safe division
try:
print(10 / 0)
except ZeroDivisionError:
print('Cannot divide by zero')Output: Cannot divide by zero
Key points
- Use 'with open()' to auto-close files
- Catch specific exceptions
- raise creates your own errors
Interview questions
Why use 'with'?
It closes the file even if an error occurs.