Exceptions

Exceptions and errors are strongly correlated, but they are different things. An exception, for example, can be gracefully handled. Here are some examples of exceptions:

0/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero len(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: len() takes exactly one argument (2 given) pi * 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pi' is not defined

In this example, three different exceptions have been raised (see the last line of each block). To handle exceptions, you can use a try...except block in the following way:

try:  a = 10/0  ...

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.