Transcription
Hello! In this lesson, we will study how to work with exception handlers in Python. Before we begin, I would like to recommend the website aeti-prager.com. On this site, you will find your homework and a lot of other useful information. The link to this lesson will be in the description of this video.
To start, let's find out what an exception is. An exception is an error that can occur during the execution of a program. If an exception, or in other words, an error occurs, the user is presented with information about it, and the program completely stops. After that, the user cannot interact with it anymore. As developers, we want to avoid such scenarios. We want the program to continue running, even if there is a fatal error. We want to ensure that the user receives some message about the error, but the program does not stop.
To achieve this smoothness and ensure that the program always runs, we need to create exception handlers. First, let's try to create an error, and later we will learn how to track it.
Let's say I want to get some information from the user. For this, I create a variable and use the input function, asking the user to enter a number. Since I expect to receive a number from the user, I wrap this function with another function called int, which is used for type conversion.
Now, let's say I want to add 5 to this variable and possibly display it on the screen. If we run the program and encounter a diligent user, they will enter a number, and everything will process without any problems. However, if we encounter a less diligent user who tries to enter a string, we will get an error called ValueError. This is exactly the type of error for which we can create exception handlers. Even if the user enters something incorrectly, everything will still be processed correctly.
Let's try to implement this. To create an exception handler, we use the keyword `try`. In the `try` block, we indicate that we are trying to implement something. Here, I include the code that was before, meaning I try to get information from the user, add 5 to it, and then display this information on the screen. If everything goes well, this piece of code will execute. But if something goes wrong, we will track it using `except`. Here, I will track the error called ValueError because that is the one that arises here.
If we encounter a ValueError, we will simply display a message to the user, saying something like "Please enter a valid number."
Now, let's try running the program again. If I enter a number, everything processes correctly. If I enter a string, there will be no fatal error. Instead, the user will see a message indicating that they should enter a valid number. Such error messages are much more pleasant to read. Additionally, the program does not terminate fatally; we simply tracked the error and displayed it to the user.
If desired, you could choose not to display anything to the user and just continue running the program. Thus, with the help of exception handlers, we can attempt to execute some code. If it executes correctly, everything is fine, and the `except` block will not trigger. But if an error occurs, we handle it and provide some information to the user, without showing any fatal errors, and the program itself will not stop, which is a very good point.
Based on this, we can create a small program. Let's say I want to ask the user to enter a number until they do so. If they enter a string, we will track the error and keep asking them to enter a number until they do.
To implement this program, I first need to create a variable, initializing it to 0. Then, I will create a loop. I will use a `while` loop because it fits our needs best. Inside the loop, we simply state that as long as `x` is equal to 0, the loop will keep running.
Inside the loop, I will write the same code I had before. I will try to get a number from the user. If I get a number, `x` will be greater than 0, and we will exit the loop. If they enter a string, we will get an error, and `x` will remain 0. I can explicitly state that it will be 0, but in reality, this is unnecessary because we haven't changed its value.
So, if they enter a string, we will track the error, display the message "Please enter a valid number," and we will again enter the loop. This will create an infinite loop until the user finally enters a number.
If we run this now, I enter a string, and it prompts me to "Please enter a valid number" again. If I enter a number, everything processes correctly, and I exit the program. But if I keep entering strings, it will keep asking me to enter a valid number until I finally do.
Now we have a complete program where we ask the user to enter a number, and we won't stop until they do.
When working with the `try-except` structure, you can track different errors. For example, I can create another error by trying to divide 5 by zero. This will raise a ZeroDivisionError, and you can also track this error. To track it, you again write a `try` block, where you try to do something, and then you write `except` to track the specific error, like ZeroDivisionError. Here, you can display a message to the user, such as "You cannot divide by zero."
Additionally, you can track other errors if needed. For example, I can add another `except` block to track a different error, like TypeError, and display a message saying "You entered something incorrectly."
If I run this now, I will get a division by zero error, and the second `except` will be ignored because the first one was sufficient. However, if I provide a valid division but then enter an incorrect data type, like using `int(input())`, and enter a string, I will get a TypeError.
If the division by zero occurs, the first handler will trigger, and the program will stop there without reaching the next `except` block. You can write multiple `except` blocks to check for various errors. The names for these errors can be taken directly from the console when an error occurs.
Another important point is that you can write a block called `finally`. This block executes regardless of whether the code in the `try` block succeeded or the code in the `except` block executed. Everything you write in the `finally` block will run. For example, I can write `finally` to indicate that this block has executed.
Suppose there are no errors; the `finally` block will still run. If there is an error, it will also run, showing that it is unaffected by the success or failure of the previous blocks. The `finally` block is particularly useful when working with files. For instance, if you try to open a file, you must ensure it is closed regardless of whether the code succeeded or not.
Additionally, there is an `else` block that executes if the `try` block runs without any errors. If any `except` block runs, the `else` block will not execute.
In summary, these constructs and keywords are essential for tracking various errors. Error tracking is a crucial topic often used when working with files, database connections, and even simple operations like division by zero or getting data from users.
In the future, do not ignore these exception handlers. Instead of simply displaying an error to the user, it is much more pleasant to provide a custom error message that you have written, avoiding any critical fatal errors being shown to the user.
Well, that concludes our lesson. I hope you enjoyed it! If so, don't forget to subscribe to the channel and join our social media. All the links will be in the description of this video.
Take care, and see you soon! Goodbye!