Exception Handling in Python — Python Technical Interview Questions & Answers
Exception Handling in Python
Exception Handling in Python
- Exceptions are errors while the program is running. 10/0, int("Asha"), open a missing file. If you don’t handle them, the script dies with a traceback. try/except lets you print a clear message and continue — or stop cleanly.
- Shape: try: risky lines. except ZeroDivisionError: handle. finally: cleanup. Don’t write bare except: — it hides bugs. Catch the type you expect. else on try runs only if no error. finally almost always runs (close file).
- Let’s dry-run. try: print(10/0) except ZeroDivisionError: print("Cannot divide by zero"). Output: Cannot divide by zero. The print(10/0) never finishes. That is the example, not a dummy pass.
- raise ValueError("amount must be > 0") when your own function gets bad input. Caller can except it. Interview: try/except/finally + one real error name.
- Exception Handling in Python — output: Cannot divide by zero. 10/0 throws; except prints the message.
try: 10 / 0
│ ZeroDivisionError
▼
except → Cannot divide
│
▼
finallyTechnical Interview Tip: Walk through try/except/finally with a file or divide example.
Code Examples for Exception Handling in Python
Example
# try-except
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
Exception Handling in Python — output: Cannot divide by zero. 10/0 throws; except prints the message.
How to Explain Exception Handling in Python to an Interviewer
Explain Exception Handling as if you are teaching a junior — definition, then one tiny script.
Try / except Finally cleanup
What does the example print, and why?
Exception Handling in Python — output: Cannot divide by zero
What mistake do freshers make with Exception Handling?
Specific exceptions