Книга: Practical Programming, Fourth Edition
Назад: Accessing Exception Details
Дальше: Raising and Chaining Exceptions

Common Built-in Exceptions

Python provides a rich set of built-in exception types (71 at the time of writing; see ). All of them are subclasses of the built-in class BaseException (subclasses are explained in the section ), but using except BaseException itself is generally a bad idea. If necessary, go for except Exception if you need a catch-all and need access to the details.

The following table lists the most frequently used built-in exceptions. An asterisk (*) next to an exception name indicates that the exception has not appeared in examples earlier in the book.

Exception Name

What Happened?

AssertionError

An assertion you made failed.

*FileExistsError

The file or directory you tried to create already exists.

FileNotFoundError

The file you tried to access does not exist.

*ImportError

The module you attempted to import was not imported successfully.

IndentationError

Your code is incorrectly indented (for example, you mixed spaces and tabs).

IndexError

You tried to access a list or tuple element with a nonexistent index.

KeyError

You tried to access a dictionary item with a nonexistent key.

*KeyboardInterrupt

You pressed Ctrl-C (or a similar key chord) to interrupt the program in the console window.

*ModuleNotFoundError

The module you tried to import does not exist in the system path (sys.path, a list of directories to search).

NameError

You referred to an undefined variable or function.

*OSError

The operating system failed to complete the operation you requested (for example, file handling, networking, or process management).

PermissionError

You attempted to access a file or resource without sufficient permissions.

StopIteration

Your generator has yielded all of its values.

SyntaxError

Your program contains a syntax error.

TypeError

You provided a value of the wrong type (for example, adding a string to a number).

ValueError

You passed an argument of the correct type but with an inappropriate value.

ZeroDivisionError

You attempted to divide by zero.

Raise the most appropriate exception and include helpful context to make errors easier to understand and fix

A well-designed function should raise appropriate exceptions to signal different error conditions. A well-written program, in turn, should handle these exceptions gracefully.

In the following sections, you’ll learn how to raise your own exceptions and define custom exception types to make your programs more robust and expressive.

Назад: Accessing Exception Details
Дальше: Raising and Chaining Exceptions