Handling errors in Python

Master “try / except” block

Girolamo Pinto
8 min readMar 29, 2022
Photo by AltumCode on Unsplash

Welcome back, fellow developers!

Today, in this guide, I want to help you to master errors handling in Python. We will discover how to manage errors made by users and how to avoid a crash system. I want to remember you that there is a list about Python and if you have no experience at all with it, I suggest you to read all those guides to understand better what we will explain here.

Link to the list.
Link to the last guide on Python about input/output and data types.

Without futher explanations let’s go catch these errors!

Managing errors

Since the computers born and computer programming with them, there was always the desire to automate and simplify the human processes. But, since the human is an imperfect machine, sometimes computer programmers should try to understand human behavior to avoid making errors or to prevent them.

In order to do so, at the beginning of computer programming, the choice for humans was so limited, because computer programmers couldn’t predict all the humans behaviors.

Programming languages came in help by creating an elegant and simple solution, giving to computer programmers and developers new methods to predict and to manage errors made by humans or by the computer itself. And most of all the OOP (Object Oriented Programming), gave to developers the opportunity to manage many human behaviors without losing perfomances or without giving to humans a limited choice when they use their code.

In this guide we will look at one these methods in Python: the try / except block. But before to go in deep let’s understand what is an error.

What is an error?

In computer programming, errors are also called exceptions. As you can read on Oracle Java Documentation:

The term exception is shorthand for the phrase “exceptional event.”

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.

It’s important to remember that a method it’s how programmers call functions in programming languages. A function, or a method as well, do something useful for the code. Inside a method you write a block of code and after calling that method the compiler execute that code.

Throwing an exception it’s the slang used when an error handling is raised by programmers to litterally catch the error before the system goes in crash. In other programming language this particular block of code is called try /catch block.

But how it works?

Let’s “try” a block of code…

When you don’t know if a particular block of code will raise an error, maybe made by the human who uses the code or maybe made by the compiler or the computer itself, it’s a good behavior to put that particular block of code in a try block. Just like says the word we try a particular code and if it works we’re so happyand we go out to party, but if it doesn’t work we shouldn’t fall in tunnel of despair and try to handle the error preventing the crash of the system.

The try block it’s made for this kind of situation, when you don’t know if the block that you’re going to execute will work or not. Obviously the try block should be matched with another block, that in Python it’s called: except.

… “except” something extraordinary happens

The except block lets you handle the error. Since the try block raises an error, the except block will be executed. Without the try block, the program will crash and raise an error.

For example let’s try to raise an error in Python. Open Command Prompt in Windows by typing on your keyboard windows button and then typing in the Search bar Command Prompt.

Once in Command Prompt let’s type python and press Enter. It should be something like this:

Now let’s write some code, for example print(x).

As you can see the code raised an error as we expected, specifically the code raised a NameError, which it means that you forgot to declare a variable or you wrote a wrong name for the variable that should be used by the code.

Obviously we know how to handle this error, we need just to declare the x variable and we’ve done. But in many other cases, it won’t be so easy.

Now let’s try to include this code in a try except block.

As you can see we put the code that generates an error in a try block and we catch the error with the except block. In the except block we put a print() which handle the error printing a message on the screen without raising an error and avoiding the system crash.

Note: Remember that in Python the indentation is really important if we don’t use the indentation the code will still generate an error.

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error. If you look at the error we raised intentionally you can easily check that is a NameError, we will use it to make our example.

As you can see the first except handled the error but the second won’t be executed, this happens because we specified the error that we want to handle and since the only error which will be thrown is the NameError.

“Else” continue the flow

And if there are no errors raised?

Sometimes could happen that our code doesn’t raise any error, maybe we were lucky or maybe we wrote a good code. But how can you continue the flow of your code without stopping the process? In our help we have the else keyword that tells to the compiler to continue to processing the code without raising an exception. Let’s see an example.

As you can see the code in the try block didn’t raise any exception, this means that the program can continue its flow, to say that we use the else keyword. The code in except block won’t be executed, because there are no errors raised by the code in the try block.

“Finally” it works

Sometimes we need to proceeed with the flow of the program regardless of whether an exception was thrown or not. For example if you are running a software and an error raises the software still works and it doesn’t shut down. To do so we need the finally keyword. The finally block, if specified, will be executed regardless if the try except block raises an error or not. Let’s see it in action.

As you can see the code in finally block it was executed even if an error was raised in the try except block. The finally block it’s useful when we work with files.

In this example we are trying to open an to write to a file that is not writable. Thanks to finally keyword the program can continue, without leaving the file object open.

“Raise” your exceptions

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword. This is very useful when you want particular behaviors in your program even if there are no specific errors raised by the compiler. For example:

As you can see in the if statement we raised our own exception by using the keyword raise and then we defined the excpetion using the Exception() method.

And obviously we can raise also some specific error. For example let’s try to raise a TypeError.

As you can see the error message appears like a TypeError message.

Sum up

To understand better what we learnt:

  • The try block lets you test a block of code for errors.
  • The except block lets you handle the error.
  • The else block lets you execute code when there is no error.
  • The finally block lets you execute code, regardless of the result of the try except blocks.
  • The raise keyword is used to raise your own exception.

I hope that you found this guide useful and interesting. For any further questions don’t hesitate to comment below, I’ll be glad to answer to your questions.

If you want you can follow me on my other social media:

References

Note: Icons taken on IconFinder website with Attribution 4.0 International (CC BY 4.0)

--

--

Girolamo Pinto

Computer Engineer student. Python developer. C# and Unity addicted. Music, food and Formula 1 lover.