Safe Exception Handling
Intermediate · Refactor · from 15 Python Pitfalls That Trip Up Even Experienced Developers
From the lesson: 15 Python Pitfalls That Trip Up Even Experienced Developers
Python is famous for being readable and beginner-friendly. But lurking beneath that clean syntax are several traps that catch even experienced developers. These aren't bugs in Python - they're features that behave differently than you'd expect.
Read the lessonRefactor this function to use specific exception handling instead of a bare except:. The function should:
ZeroDivisionError and print "Error: division by zero"TypeError and print "Error: invalid types"Test with safe_calc(10, 2), safe_calc(10, 0), and safe_calc(10, "a").
def safe_calc(a, b):
try:
result = a / b
except:
print("Something went wrong")
else:
print(result)
safe_calc(10, 2)
safe_calc(10, 0)
safe_calc(10, "a")
More Common Pitfalls exercises
- Fix the Mutable DefaultIntermediate
- Predict the Output: Late BindingIntermediate
- Safe List FilteringIntermediate
- Fix the Bug: Shallow Copy SurpriseIntermediate
- Predict the Output: Variable ScopeIntermediate
- Build a Safe Defaults FunctionIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz