Python raises exceptions for errors—try/except/else/finally handles them. Unlike some languages, exceptions are the normal control path for many error cases, not only catastrophes.
try / except / else / finally
try:
value = int("42")
except ValueError as e:
print("bad input", e)
else:
print("parsed", value)
finally:
print("cleanup always runs")
Raising and custom exceptions
raise ValueError("expected positive number")
Catch specific exceptions first—avoid bare except: that swallows KeyboardInterrupt. Use raise to re-raise and preserve traceback.
Important interview questions and answers
- Q: else on try?
A: Runs only if no exception occurred—good for code that should not run if try failed. - Q: EAFP vs LBYL?
A: "Easier to ask forgiveness"—try/except; "Look before you leap"—check conditions first. Python culture favors EAFP for many cases.
Self-check
- When does finally run?
- Why avoid bare except?
Tip: Catch specific exceptions—bare except: hides bugs and KeyboardInterrupt.
Interview prep
- else on try?
Runs if no exception in try—keeps success path separate from except blocks.
- EAFP vs LBYL?
Python favors try/except (easier to ask forgiveness) for many error cases vs pre-checking everything.