Functions and errors
Handling errors
Goal: Read tracebacks and handle exceptions · 10 min
When something goes wrong at runtime, Python raises an exception and prints a traceback. Read it from the bottom: the last line names the error type and message, the lines above show where it happened.
Frequent types: NameError (unknown name), TypeError (wrong type, e.g. "a" + 1), ValueError (right type, bad value, e.g. int("abc")), IndexError, KeyError, ZeroDivisionError.
Handle expected problems with try/except:
try:
n = int(text)
except ValueError:
n = 0
Catch specific exceptions; a bare except: hides real bugs.
Worked example: Safe division
- try runs the risky code.
- Dividing by 0 raises ZeroDivisionError.
- The except block runs instead of crashing.
def safe_div(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_div(6, 3), safe_div(1, 0))Output:
2.0 None