Last Updated:

Exceptions in Python

Exceptions in Python

Exceptions are constructs that allow you to catch a code execution error.

During the writing of the program, mistakes are made, sometimes ridiculous, and sometimes destroying the entire program. In general, errors can be decomposed into two categories: logical and factual.


A logical fallacy is an error in an algorithm. Not that comparison mark, re-assigning an existing variable, not the number of loop passes, not having a loop counter, and the like. The main feature of this error is that it is quite difficult to track it, since you need to look for it "with your hands".


A factual error is one that is very obvious. Dividing by zero, overflowing the array, going beyond the array boundary, accessing a non-existent element, and so on. This kind of error will be pointed out to us by the interpreter himself.

When we try to divide a number that is greater than zero by zero, we get an error.

Note that the output function did not work.

The lowest line of "ZeroDivisionError" is the name of the error, through the colon there is a description of it.

In this way, the interpreter informs us of many factual errors.

The main trouble is that after such an error occurs, our program "crashes", the program crashes and all the code that is after the code with the error does not work.
A factual error occurred -> the interpreter gave an error -> the program
terminated This is not a complicated scheme.

But this option does not suit us, we need the program to work all over. And here exception handling will help us!

Three keywords will be our salvation:

  1. try — "trap" block, the code in which the error can occur is placed in it;
  2. except - A filter block that contains the name of the error and the code that must be executed if this error occurs. There can be as many "filters" as one "trap";
  3. finally is a "skip" block in which the code is placed, which must be executed independently of the "filters". There can be only one "pass" per "trap";

Let's put it all together:

  1. The "trap" places the code in which the error may occur;
  2. "Filters" with the code that will be executed in the event of this particular error are tied to the "trap";
  3. If desired, you can create a "skip" block with some code that will be executed regardless of whether there were errors or not;

Let's consider the same example with division by zero.

We divided by zero, but we displayed the message "HAHAHAH".

You can not specify the name of the error and then ALL errors will be processed, but this is not good programming tone, it is impossible to understand what kind of error occurred in the program. But sometimes, it's the best solution.

 

In such a simple way, we dealt with the "exceptions in Python"!