Python 3D Academyবাংলা

Errors & Exceptions in Python

Chapter 18: Errors & Exceptions

5 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.