Editor

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 lesson

Refactor this function to use specific exception handling instead of a bare except:. The function should:

  • Catch ZeroDivisionError and print "Error: division by zero"
  • Catch TypeError and print "Error: invalid types"
  • Print the result for valid inputs
  • 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

    All Python exercises · 50 practice problems · Advanced Python quiz