47
Error Handling
Error Handling: Fail Gracefully, Don't Crash
What might confuse you right now
"Does getting exceptions mean my code is bad?"
Not necessarily. Many exceptions come from external input, network issues, or the file system. The key is handling them in a controlled way.
One-line definition
Error handling uses try/except/else/finally to manage error branches and cleanup logic.
Real-life analogy
GPS hitting a road closure isn't the end of the trip -- it just reroutes automatically.
Minimal runnable example
try:
num = int("abc")
except ValueError:
print("Invalid input format")
Full structure
try:
x = 100 / int(input("Enter a divisor: "))
except ValueError:
print("Please enter an integer")
except ZeroDivisionError:
print("Cannot divide by 0")
else:
print(x)
finally:
print("Done")
Quick quiz (5 min)
- Implement a safe division function.
- Distinguish and handle two exception types.
- Log the error text.
Quiz answer guidelines & grading criteria
- Answer direction: working code that covers core conditions and edge inputs from the prompt.
- Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
- Criterion 2 (Readability): Clear variable names, no excessive nesting.
- Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.
Transfer task (homework)
Add error handling and fallback output to a file-reading script.
Acceptance criteria
You can independently:
- Write type-specific exception handling
- Understand when
else/finallytrigger - Preserve actionable error information
Common errors & debugging steps (beginner edition)
- Can't understand the error: read the last line for the error type (e.g.,
TypeError,NameError), then trace back to the relevant code line. - Not sure about a variable's value: temporarily add
print(variable, type(variable))at key points to verify data matches expectations. - Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.
Common misconceptions
- Misconception: A bare
exceptthat catches everything is fine. - Reality: Catch specific exceptions first, use a generic fallback only as a last resort.