What an exception is

An exception stops the program at the line that failed

print('start')x = int('abc')print('end')prints start'abc' is not a number: Python raises ValueErrornever runsWhat appears on the screenstartTraceback (most recent call last): File "prog.py", line 2, in <module> x = int('abc')ValueError: invalid literal for int() with base 10: 'abc'An exception stops the program at the line that failed.An exception is Python reporting, while the program runs, that a line cannot be carriedout. Unless something catches it, the program ends there and prints a traceback.

An unhandled exception ends the program with a traceback.

What an exception is · Going deeper

Reading a traceback, and SyntaxError

In the tracebackWhat it tells youline 2Where the program was when it failedx = int('abc')The line itselfValueErrorThe type of exception: the name you write after exceptinvalid literal for int() ...: 'abc'A message with the detailsA different kind of errorx = int('abc' with no closing bracketSyntaxError: found before the program startsNothing runs at all: not even start is printedRead a traceback from the bottom: the last line names the exception.A SyntaxError means the code could not be read. An exception means it was read, and failed while running.

Read from the bottom: the last line names the exception.

Built-in exceptions

Each kind of mistake raises its own exception

int('abc')ValueErrorthe right type, but a value that cannot be used'a' + 1TypeErroran operation on the wrong type1 / 0ZeroDivisionErrordividing by zero, also with // and %[1, 2][5]IndexErrora position past the end of a sequence{'a': 1}['b']KeyErrora key the dictionary does not haveprint(y)NameErrora name that was never assignedEach kind of mistake raises its own exception.The name tells you what went wrong: the value, the type, the arithmetic, the position,the key or the name.

ValueError, TypeError, ZeroDivisionError, IndexError, KeyError, NameError.

Built-in exceptions · Going deeper

Near misses

CodeGivesNoteint('3.5')ValueErrorA string with a point is not an int literalint(3.5)3A float is fine: the fraction is dropped'2' + 3TypeErrorstr + int is not defined'2' * 3'222'str * int is: repetitionlen(5)TypeErrorA number has no length[1, 2][-3]IndexErrorToo far back is out of range too[1, 2][1:9][2]A slice never raises IndexError{'a': 1}.get('b')Noneget() does not raise KeyError{'a': 1}[0]KeyErrorA dictionary has keys, not positionsValueError or TypeError? Ask whether a different value of the same type would work.int('7') works, so int('abc') is a ValueError. No number makes 'a' + 1 work, so that is a TypeError.

Would another value of the same type work?

Check yourself

d = {'a': 1}print(d[0])

Which exception does this raise?

try and except

except catches the error and the program carries on

try: x = int('abc') print('ok')except ValueError: print('bad number')print('end')try: watch the lines belowraises ValueError: the rest of the try block is skippedthe error is a ValueError, so this branch matchesprints bad numberthe program carries on: prints endskippedexcept catches the error and the program carries on.Put the risky lines under try. If one of them raises the exception named after except,Python jumps straight to that branch, runs it, and continues below. No traceback.

try the risky lines. except handles the failure.

try and except · Going deeper

No error, and the wrong error

The same try block, with a different first lineFirst line of tryRaisesPrintedNotex = int('7')nothingok, endNo error: the except branch is skippedx = int('abc')ValueErrorbad number, endCaught: the branch runsx = 1 / 0ZeroDivisionErrora tracebackNot a ValueError: nothing catches it,and end is never printedtry: with no except branch is a SyntaxError. except: with no name catches every exception.An except branch catches only the exception it names.Anything else passes straight through, as if the try were not there.

A branch catches only what it names.

Several except branches

Python runs the first except branch that matches

try: n = int(text) print(10 / n)except ValueError: print('not a number')except ZeroDivisionError: print('zero')text = '5'2.0no error: both branches are skippedtext = 'abc'not a numberint() raises ValueError: first branchtext = '0'zerothe division raises ZeroDivisionError: second branchPython tries each except in order and runs the first that matches.At most one branch runs for any one error.

One try, several except branches, at most one runs.

Several except branches · Going deeper

Grouping, and the bare except

CodeWhat it doesexcept (ValueError, TypeError):One branch for two exception typesexcept:Catches whatever is left. It must be the last branchexcept: before except ValueError:SyntaxError: default 'except:' must be lastexcept Exception:Catches all the ordinary exceptions, these six includedtwo branches that both matchOnly the first one runsan error raised inside an except branchNot caught by the branches beside itOrder the branches from the most specific to the most general.A bare except hides every mistake, a misspelt name included, so use it sparingly.

Specific first. Bare except: last.

Check yourself

try: print([1, 2][2])except KeyError: print('K')except IndexError: print('I')

What does this print?

Tracing the flow

An exception travels back through calls until it is caught

def half(n): return 10 / ntry: print(half(0)) print('done')except ZeroDivisionError: print('caught')print('end')def stores the functionthe call goes into half10 / 0 raises ZeroDivisionError inside the functionno except in half, so the error travels back to the caller, and matches hereprints caughtprints endskippedAn exception travels back through the calls until an except catches it.The try block protects everything that runs inside it, including the functions it calls.If no caller catches the exception, the program ends with a traceback.

Raised in half, caught by the caller. Prints caught, end.

Tracing the flow · Going deeper

Check first, or catch after

ExceptionCheck firstOr catch itZeroDivisionErrorif n != 0:except ZeroDivisionError:KeyErrorif k in d: or d.get(k)except KeyError:IndexErrorif i < len(a):except IndexError:ValueErrorno simple check for int(input())except ValueError:TypeErrorfix the codeusually a bug, not something to catchNameErrorfix the codeusually a misspelt or missing nameCatch what can go wrong with good code. Fix what is simply wrong code.Bad input from a user is expected, so it is handled. A misspelt name is a mistake, so it is corrected.

Handle bad input. Fix bad code.

Check yourself

def f(d, k): try: return d[k] except KeyError: return 0print(f({'a': 1}, 'b') + f({'a': 1}, 'a'))

What does this print?

Lesson complete

You finished “Exceptions”

Answer the questions along the way to see your score here.

Open in a new tab