Errors & Exceptions in Python
Chapter 18: Errors & Exceptions
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Catching errors with try and except
Put risky code in a try block, and if it raises the error named in except, Python runs the except block instead of crashing, then carries on.
Several excepts, else and finally
Python checks the except blocks from the top and runs the first one that matches; else runs only when the try had no error, and finally runs always.
Raising your own errors
raise ValueError("message") stops a function on purpose when it gets a value it can't work with, and the error travels to whoever called it.
Errors travel up
An error raised inside a function travels up the call stack, out of each function in turn, until some try catches it, or the program stops with a traceback listing every call it passed through.
Chaining errors with raise from, and logging what happened
raise NewError(...) from err raises a clearer error and keeps the original one as its cause, and the logging module records what a program does, with a level on every message, instead of scattering print calls.