Module (14%)
Section (14%)

Exceptions - short introduction

When Python executes a script and encounters a situation that it cannot cope with, it:

  • stops your program;
  • creates a special kind of data, called an exception. Of course, this exception is an object.

Both of these activities are called raising an exception. We can say that Python always raises an exception (or that an exception has been raised) when it has no idea what do to with your code.

What happens next?

  • the raised exception expects somebody or something to notice it and take care of it;
  • if nothing happens to take care of the raised exception, the program will be forcibly terminated, and you will see an error message sent to the console by Python;
  • otherwise, if the exception is taken care of and handled properly, the suspended program can be resumed and its execution can continue.

Python provides effective tools that allow you to observe exceptions, identify them and handle them efficiently. This is possible due to the fact that all potential exceptions have their unambiguous names, so you can categorize them and react appropriately.

You may already have met an exception error message like the following:

IndexError: list index out of range

output


Sooner or later, every Pythonista will write a code that raises an exception, and that is why it is so important to know how to deal with exceptions.

ups3.png

Python comes with 63* built-in exceptions, and they can be represented in the form of a tree-shaped hierarchy. The reason for this is that exceptions are inherited from BaseException, the most general exception class.

And this approach tells you that you can also create your own specific exception classes – the only constraint is: you have to subclass BaseException or any other derived exception class.

  • * This number may vary across different Python versions.