Exceptions
We have already met the exceptions in the previous parts. These exceptions happen when something goes wrong in the code generating an error. The reasons why these errors are generated can be many, for example due to a resource not found for example a file, or to a value with a format not compatible for a particular operation, etc.
For example, a very common mistake is when you have a division by zero. The exception that is generated is ZeroDivisionError.
>>> 5/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
When the execution of the code leads to an error an exception is generated (Exception), and if not managed in some way, the execution is interrupted.
Python already has many exceptions already implemented in the system, each specific for a particular type of error. Some of the most common exceptions are:
ImportError – when the import of a module fails
IndexError – when looking for an element of a list using an index beyond its size (out-of-range)
NameError – when referring to a non-existent variable (very often not visible)
SyntaxError – when the code contains a syntax error
TypeError – when the type of a value does not match what is required or is not recognized
>>> 4 + "1"
ValueError – when the value type is correct but its value is incorrect
⇐ Go to Chapter 3.8 The Standard Library and pip
Go to Python Lesson 4.2 – Handling Exceptions ⇒