Contents

Programming Fundamentals › Error Handling

Exception

An object signalling an error that unwinds the call stack until caught.

Also known as: exceptions, runtime error

An exception is an object that signals an error. When code throws one, normal execution stops, and the exception travels up the call stack through the callers until something catches it. If nothing does, the program crashes with a stack trace.

def read_age(text):
    return int(text)               # raises ValueError for "abc"

try:
    age = read_age(user_input)
except ValueError:
    print("Please enter a number")

Exceptions let the code that notices a problem (deep inside) be separate from the code that knows what to do about it (higher up), without passing error codes through every function.

Common ones

PythonMeaning
ValueErrorright type, bad value
TypeErrorwrong type
KeyError / IndexErrormissing key or position
FileNotFoundError, OSErrorfile and system problems
ZeroDivisionErrordivide by zero

JavaScript has TypeError, RangeError, and others, all inheriting from Error.

What an exception carries

A type, a message, and a stack trace showing where it happened. Reading them is the first debugging step (reading error messages).

Habits