DEV Community

Cover image for Handling Exceptions In Python
Emmanuel Tanimowo
Emmanuel Tanimowo

Posted on • Originally published at


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.

What is an Exception?

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.

carbon (10).png

Fig 1.0

carbon (11).png

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).

We can improve the error-resistance of this program by enclosing it in a try-except-else block. When the program is run, if no exceptions are raised, the statements in the else block are executed after the statements in the try block. But if an exception is raised, the statements in the else block are skipped. The following is the general structure of a try-except-else block.

carbon (13).png

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.

carbon (14).png

Fig 1.2

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.

carbon (15).png

Handling multiple exceptions in your program

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.

carbon (17).png

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.

carbon (16).png

Fig 1.4

Using one except block to handle all exceptions

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.

carbon (19).png

Fig 1.5

Displaying an exception's default error message

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.

carbon (20).png

Fig 1.6

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.

carbon (21).png

Failing Exceptions Silently

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.

carbon (23).png

Exception handling with the Finally keyword

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.

carbon (22).png

Fig 1.7

What happens if an exception isn't handled?

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.

This is the last section of the article. Thank you for taking the time to read through; if you found the content useful, you can subscribe to my newsletter to be notified when new articles are published.

I'd like to connect with you as well, so let's connect on:

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.