Introduction to Exceptions in Python
This section will cover exceptions in Python. First, we need to understand what they are.
When writing any program, the developer implicitly expects that all software and hardware mechanisms used will work correctly.
This, however, is not always the case. When transmitting data over the network, the connection is broken and the data arrives to us in an incorrect form, or does not arrive at all. When writing a file, it turns out that the space allocated to us on the hard drive has run out, and the file cannot be written. When reading a file, it turns out that such a file does not exist and we have nowhere to read it from. When printing data on a printer, the cable connecting the printer and the computer breaks.
All the situations described have a common essence: some kind of failure occurs, which leads to the impossibility or senselessness of completing the planned operation.
There are also situations in which some error occurs that is not a failure. For example, you ask the user for his email, and he enters the email in an incorrect format. It is clear that our program cannot continue processing the email, since it is incorrect. However, this is not an exceptional situation. Our program can correct the situation itself: it will display an error message and the user will repeat his input.
In fact, the difference between a failure and not a failure is quite fuzzy. An event that one program might treat as an exceptional situation, another program might treat as some kind of error that it can handle.
The criterion here is this: if when a problem occurs your program can continue to do what it is designed to do, then it is not an exceptional situation, but if it cannot, then yes, it is an exception.
For example, we have a program that should ask the user for an email. If the user enters an email in an incorrect format, this is not a failure. This is an expected problem, and our program will ask the user for an email as many times as he enters it correctly.
Let's say our program that asks for an email should also send this correct email via the Internet. It turns out that the Internet is not working. Now that's a problem: the program will not be able to send data via the Internet if the Internet is not working. The program, however, can continue its execution: it can display information about the problem, try to send it again after some time, and so on. But these actions are not quite what the program was intended for, since the program will not be able to do the main action - sending an email.
Based on this, very often the interpretation of what behavior will be considered normal and what exceptional depends on the tasks facing the programmer.