01 logo

Exception Handling in Python

Simple and complete guide to handling exceptions in python

By Estefanía NoguerónPublished 3 months ago 5 min read
Like
Exception Handling in Python
Photo by Markus Winkler on Unsplash

Most programming languages provide us with tools to deal with cases where things don't work as expected. In Python, it is done through the language's exception system by creating an exception object, which will allow us to handle errors that arise during the execution of a program.

Exceptions in Python can occur in two ways, unexpectedly (when the developer doesn't consider that statement/script could cause an error) or expected (when the developer takes into account what errors they might face and considers them ).

Note: in both cases, if the exception is not handled correctly, it will stop the execution of the program and print an error message indicating where the problem is.

As in real life, when we are not aware of what can go wrong, we cannot prepare ourselves to solve it. However, when we know where there may be problems, we will put the mechanisms to work to avoid them. The same will happen in your scripts.

What is the difference between syntax errors and exceptions?

Now, not all the issues that interrupt the execution of a program are due to an exception, it can also be due to a syntax error. Although these two terms are often used interchangeably when talking about Python, we must be careful because they are different.

Syntax errors occur when we write a statement of Python code that is not syntactically valid. The Python interpreter indicates these errors with the term SyntaxError and tells us where the error is. For example, when we need to close a parenthesis:

A syntax error is not an exception. These types of errors cannot be handled, they will stop the execution of the program and do not correspond to exceptions within the language. They must be corrected before the execution can continue.

Exceptions correspond to errors that occur in statements of Python code that may be syntactically correct. These types of errors are not fatal to the program and can be managed or ignored. They can arise, for example, by referencing a variable that does not yet have a value, comparing two variables that are not comparable, etc.

The above errors are syntactically correct, these are caused by other problems, such as not having defined the variable previously, trying to divide by 0, or adding a string and an integer.

'try' and 'except' Statements.

In Python, exceptions are handled by wrapping the code with try and except statements. Python executes the code after the try statement as a normal part of the program. If an error is detected in this 'try' block, the except block will be executed. If any exception occurs and is considered to be handled, the normal flow of execution will follow, however, if that exception is not considered, execution will be interrupted and the exception will propagate to higher calls.

In the following example, we indicate to the exception that, if at the time of executing the variable 'var' is not defined, catch the error (NameError) and assign it 'Hi everyone!'. The above is to avoid the interruption of the program. Once this code is executed, the variable var will already have that new value.

In addition to the above syntax, we can catch multiple exceptions simultaneously using multiple except blocks. In the following example, we handle the IndexError exception, for cases where the index is out of range.

What would happen if we want to avoid the interruption of the execution? As we have said, there are a lot of exceptions and it will be difficult to control all of them, for this, we can use the 'Exception' object. This object will catch any previously unhandled exception type. A good practice is to collect this object in a variable to avoid losing information about possible exceptions.

There are a large number of exceptions recognized by Python, which you can consult in the official documentation of the language

Custom Exceptions

As we have already seen, in Python exceptions are automatically raised when an error or unexpected action occurs, but it is also possible to intentionally raise exceptions using the raise statement. That is, we can create our own exceptions.

In the following example, we ask the user to enter her name, which must be written with the first letter capitalized. If the first character is not an upper case or is not a letter, it will throw the following exception:

AssertionError and finally

As a complement to all the previous statements, Python provides us with an additional statement that allows us to verify at a certain point in our program that everything is working properly. This is the assert statement. This is very useful so that you do not have to wait for an error to occur to know that everything is working correctly. That is, I can force at a certain moment to check if everything is working correctly and if not, an exception is thrown.

In the following example, I ask the user to enter a password of at least 8 digits on the screen. Now, I check that the password does indeed have equal to or more than 8 digits using the assert statement. If not, it will throw an exception (after the comma):

Python provides us with the last statement that we can use to clean up or close objects after the execution of our code when handling an exception. This statement is called finally and the code located in its body will always be executed, regardless of whether the exception occurs or not. It allows executing some code regardless of the result of the try and the except.

The following example is intended to simulate a simple login. The user inserts a password (which must be at least 8 digits). If it is correct, the 'else' fragment will be executed since there was no exception and the variable 'password' will be removed. As shown below.

What would happen if the password was not correct and the exception was thrown?

As we can see, despite having thrown the exception or not, the variable 'password', upon reaching the end of the code execution, is eliminated from the namespace of the program (whether the exception is raised or not).

I hope this article has been useful to you. If so, please give me a 'clap' and click 'Follow'. Your support is very important to be able to continue writing on this platform. Cheers!

apps
Like

About the Creator

Estefanía Noguerón

Developer and writer about educational content of programming and data analysis with Python. I am passionate about Machine and Depp Learning.

More about me here: https://www.linkedin.com/in/estefan%C3%ADa-noguer%C3%B3n-90770915a/

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2023 Creatd, Inc. All Rights Reserved.