Handling Exceptions In Python
Tags: python, beginners, programming, codenewbie
Published: 2021-12-05 21:28:51

Things rarely go as planned, especially in the world of programming. Errors are unavoidable when writing code, which can be frustrating at times. 

<iframe src="https://giphy.com/embed/wMvESGxZ0Cqd2" width="480" height="350" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/frustrated-ryan-gosling-wMvESGxZ0Cqd2">via GIPHY</a></p>

In this article, I'll show you how to handle exceptions in Python.

<hr>

### 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637251911162/ljPlx3RtS.png)
##### ***Fig 1.0***

![carbon (11).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1637311138943/V-Z41wY8F.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).
<hr>
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637312685830/TqzRzhqpK.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637315054681/tNoW6oxuN.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637317733468/mO9GWoDKO.png)
<hr>
### 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](https://www.tutorialsteacher.com/python/error-types-in-python) 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637320800936/9aI7hgo5l.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637318180781/W8SyzoJQq.png)
##### ***Fig 1.4***
<hr>
### 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637323598463/88QZphgMFu.png)
##### ***Fig 1.5***
<hr>
### 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637327137209/RpQE2M8qR.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637327705948/3HZfsdTxJ.png)

<hr>

### 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637331221817/8a3f3tlbL.png)

<hr>
### 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1637330061076/gq72bJcJbn.png)
##### ***Fig 1.7***

<hr>
### 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.

<hr>
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](https://mannuel.hashnode.dev/) to be notified when new articles are published.

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

- [Twitter](https://twitter.com/emma_tanimowo)
- [LinkedIn](https://www.linkedin.com/in/emmanuel-tanimowo-6122291aa)