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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.