19
Handling Exceptions In Python
Things rarely go as planned, especially in the world of programming. Errors are unavoidable when writing code, which can be frustrating at times.
In this article, I'll show you how to handle exceptions in Python.
An exception is an error that occurs while the program is running. In some cases, an exception may cause the program to stop or produce unexpected results. For example, taking a look at Fig 1.0. This program gets two numbers from the user and divides the first number by the second number, and displays the result. However, when the program is run, an exception occurs as shown in Fig 1.1.
The error message displayed in Fig 1.1 is called a traceback. A traceback provides information about the line number(s) that resulted in the exception. In Fig. 1.1, the last line of the error message shows the name of the exception that was raised (ZeroDivisionError) and a brief description of the error that caused the exception to be raised (integer division or module by zero).
Let's put the try-except-else block to work on the program now. As shown in Fig 1.2, we ask Python to try to complete the division operation in a try block, which includes only the code that could cause an error. Any code that is dependent on the try block's success is added to the else block. In this example, if the division operation is successful, the result is displayed using the else block.
The except block also tells Python how to handle a ZeroDivisionError. A message is displayed if the try block fails due to a division by zero error.
The code in a try block can often throw multiple types of exceptions. You must write an except block for each type of exception you want to handle in such instances. Here's a link to a resource that explains in detail the different types of exceptions that could occur in your program.
A ZeroDivisionError may occur if we attempt to divide a number by zero. In addition, if incorrect input is entered, such as twelve, which has a string data type, a ValueError may occur, and an exception is raised when Python tries to convert a string to an integer as shown in Fig 1.3.
Fig 1.4 shows us how we can handle the two exceptions. If an exception occurs in the try block, Python examines each of the except blocks in the try-except block from top to bottom. It branches to an except block that specifies a type that matches the type of exception that occurred when it finds one. Python displays the result if none of the except blocks specify a type that matches the exception.
The previous example showed us how we could handle two types of exceptions individually in a try-except block. Sometimes you might want to write a try-except block that simply handles any exception raised in a try block and responds the same way regardless of the exception's type. In a try-except block, you can accomplish this by writing one except block that does not specify a particular type of exception as shown in Fig 1.5. If any exception is raised, a friendly message is displayed to you.
When an exception is raised, an object known as exception object is created in memory. If an exception goes unhandled, the exception object usually contains a default error message about the exception, which is the same error message that appears at the end of a traceback. You can optionally assign the exception object to a variable when writing an except block, as shown here:
except ValueError as err
This catches ValueError exceptions; the expression following the except block specifies that the exception object is assigned to the variable err. The name err isn't particularly memorable. That is simply the name we have chosen for the sake of illustration. You are free to use any name you want :). After that, you can use the print function to display the default error message by passing the err variable. Figure 1.6 shows an example of how this is accomplished.
Fig 1.6 shows how to display an exception's default error message. You can also write each except block to display the default error message of any exception that should be raised.
Furthermore, if you only want one except block to handle all of the exceptions raised in the try block, you can specify Exception as the type as shown below.
When an exception occurred in the preceding examples, an error message was displayed. However, you may not want to disclose every exception you encounter. When an exception occurs, you may wish the program to fail silently and proceed as if nothing happened. To have a program fail silently, construct a try block as usual, but in the except block, use the pass keyword to specifically tell Python to do nothing, as seen below.
Finally is a keyword in Python that is always executed after a try-except block. Even if the try block throws an exception, any code written in the finally block will always be executed. Fig 1.7 shows an example of how that is done.
The program will terminate if an exception is not handled. There are two ways that a thrown exception can go unnoticed. The first option is for the try-except block to have no except blocks that define the appropriate exception type. The second option is for the exception to be raised from outside of a try block. In any instance, the program will come to a halt due to the exception.
I'd like to connect with you as well, so let's connect on:
19