Python: “try-except-finally” Usage Explained!

In this article, let us learn about the “try-except-finally” mechanism in Python.

For those of you in a hurry here is the short version of the answer.

“try-except-finally”: In a Nutshell

The try-except-finally is a set of statements provided by Python to handle exceptions effectively.

They each have a role and function as described in the following table:

tryHolds the code that might raise an exception
exceptHolds the code to run in-case the try block raises an error
finallyHolds the code that must be executed before leaving this try-except block
Here’s how that would look in code:
try:
    # code that might raise an exception
except:
    # alternate code that will be executed when the code in the try clause is not executed
finally:
    # code that must be executed before leaving this try-except block

Here is a simple example

try:
    print("This is the try block code")
except:
    print("This is the except block code")
finally:
    print("This is the finally block code")

This will produce the following output

This is the try block code
This is the finally block code

Here the except block is not executed as no error was raised in the try block.

Here is another example where the try block raises an exception.

try:
    x = 1/0
    print("This is the try block code")
except:
    print("This is the except block code")
finally:
    print("This is the finally block code")

This will produce the following output.

This is the except block code
This is the finally block code

Here the except block is executed and then the finally block is executed.

The try-block does not print anything as it raises an exception on line-2 which causes the execution to jump to line-4 (skipping the print statement on line-3)

The finally block comes with the following 2 quirks which makes it especially useful in certain situations where a clean-up code is needed. (explained in detail later on in the article)

  • The finally block is executed before handling any uncaught exceptions &
  • In case the try-except-finally is inside of a function, the finally block gets executed before any return statement is executed

Here is a pro tip for you, to fix any error in Python. Whenever your program crashes with an Exception, (take a deep breath and) have a look at the huge wall of error text that just got printed on your screen!

There is actually a lot of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

Don’t worry if the above answer does not make sense to you as that was targeted at more experienced programmers who just wanted to refresh their memories. The rest of this article is dedicated to those of you in the first steps of your journey to becoming a Python Craftsman.

By the time you reach the end of this article, I suggest you come back and read this summary once more, I assure you it will make much more sense then!

“try-except-finally”: A Thorough Explanation

I remember the time when I first came across the try-except-finally structure in Python. I must say this combination of keywords was not intuitive at all for me to understand what was going on with the code. If you feel like you are sailing in the same boat, then this article is for you!

The Fundamentals: Exceptions, What are they?

If you fill your car’s fuel tank with water instead of gas, the engine will have no idea what to do with it and the engine will simply refuse to run.

Similarly, when the “Python interpreter” (the engine) does not know what to do with the “data” (water) that we gave it, the program will get stuck. The Exception object is just an error report generated by the interpreter giving us clues on

  • what went wrong? and
  • where in the program the problem is?

Sure there is more to Exception than that, but their main use is to give us clues. So the next time when you think about exceptions, think of a them as clues to solve an issue!

If you feel that your basics could use some boosting, I suggest reading the following article

Exceptions in Python: Everything You Need To Know!

If you are a visual learner, here is an interesting video we made on that topic!

Lets get back to the topic and start by breaking it down and taking a look at each of these keywords individually, starting with the try block.

try

The try block is the first of these blocks. We can place our code that might raise an error inside this block. 

We can use this by simply typing the keyword try and then placing the code inside its block:

try:
    #your code that might raise an error goes here

When an exception occurs in Python, the program is usually stopped. Look at this statement, it raises an error as we are not allowed to divide a number by 0, it is mathematically invalid:

x = 1/0

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(1/0)
ZeroDivisionError: division by zero

If you wish to learn the tricks behind utilizing the error text the right way to solve bugs, we have an excellent article written on that topic which you can find in the link below!

Python: Details contained in an Exception

Let’s use the same error-inducing code but with the try clause this time to see what will be different:

try:
    print(1/0)

You might ask what now?

Should we execute the above try block?

Not yet, python does not allow us to execute the try block by itself separately, we have to execute the except (or finally) block along with it, so let’s look into that shall we?

except

The except block is where we keep the code to be executed if the try block’s code raises an exception.

Let me say that again,

If the try block raises an error during execution, the Python interpreter will stop executing the code in the try block and jump to the except block.

If the code in the try block does not raise an error, the try block will finish executing and the except block will be skipped this time.

For visual learners:

The way to implement except is the same as try, just use the keyword and place the code inside its block.

Let’s look at two pieces of code that use except, one without an error and one with it:

Code without error

try:
	print ("Starting try block...")
	x = 10/5
	print ("The try-block has finished executing!")
except:
	print("Your code has an error in it!")

print("Exiting...")

OUTPUT

Starting try block...
The try-block has finished executing!
Exiting...

Here

  • the try-block finished executing without an error
  • lines 2 and 4 get printed in the output
  • except block is skipped since no exception was raised
  • the program exits printing line-8

Code with error

try:
	print ("Starting try block...")
	x = 10/0
	print ("The try-block has finished executing!")
except:
	print("Your code has an error in it!")

print("Exiting...")

OUTPUT

Starting try block...
Your code has an error in it!
Exiting...

Here

  • the try-block started executing
  • line-2: print (“Starting try block…”) ran without issues and we see that in the output.
  • line-3: x = 10/0 raised an exception as it is not possible to divide by zero.
  • Python stopped executing the try block and jumped to the except block.
  • line-6: print(“Your code has an error in it!”) gets executed and we see that in the output
  • the program exits printing line-8

I hope with this example the picture below makes much more sense!

It is worth mentioning that this section only scratched the surface of how to use the except block, if you wish to wield the power of except like a pro, I suggest setting 30mins time aside for the following articles!

Exceptions in Python: Explained for Beginners!

Python catch multiple exceptions

Python: “except Exception as e” Meaning Explained!

Alright, it’s time to move on to the last piece of the puzzle: the finally block!

The finally block and its quirks

The finally statement is an optional but a very handy keyword that we can use with the try-except statements.

The finally block is placed as the last block in this mechanism and the way it functions is simple, the code in this block will always be executed!

The flowchart below depicts this logic

This will translate into code like this

try:
    # code that might raise an exception
except:
    # alternate code that will be executed when the code in the try clause is not executed
finally:
    # code that must be executed before leaving this try-except block 

If you read the above flowchart and code syntax keenly, the following questions will pop up in your head.

Why don’t we just eliminate the finally block and just place whatever code that was inside the finally block outside the try-except like this?

try:
    # code that might raise an exception
except:
    # alternate code that will be executed when the code in the try clause is not executed


# whatever code that need to be executed after the execution of try and except blocks

The answer is

The finally block will get executed even if an exception gets raised in the except block.

embeddedinventor.com

For example, consider the code below.

try:
    x = 1/0
except ZeroDivisionError:
    print("Error: Invalid input, you cannot divide a number by 0.")
    raise ValueError

print("Exiting the program")

This will result in the following output

Error: Invalid input, you cannot divide a number by 0.
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    x = 1/0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
main    raise ValueError
ValueError

As you can see the last part “Exiting the program” never got printed.

But if you place it inside the finally block like this

try:
    x = 1/0
except ZeroDivisionError:
    print("Error: Invalid input, you cannot divide a number by 0.")
    raise ValueError
finally:
    print("Exiting the program")

you will get an output like this

Error: Invalid input, you cannot divide a number by 0.
Exiting the program
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    x = 1/0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    raise ValueError
ValueError

If you look closely, at line-2 of the output above you can see that the finally statement got executed before the raise statement in line-5 above got executed!

Cool isn’t it!

The same goes for uncaught exceptions from the try block too!

Another interesting property of finally keyword is its relationship with the return keyword.

Consider the example below.

def myFunction():
	try:
		x = 1/0
                print("try block finished successfully")
	except ZeroDivisionError:
		print("Error: Invalid input, you cannot divide a number by 0.")
		return
	finally:
		print("Exiting the function")
		
		
myFunction()
print("Exiting the program")

Here we have a return statement placed on line-7 in the except block.

If we run the code above we will get the following output

Error: Invalid input, you cannot divide a number by 0.
Exiting the function
Exiting the program

Here

  • line-3 “x = 1/0″ raises a ZeroDivisionError
  • line-4 is skipped and the execution jumps to line-5, which catches this exception
  • line-6 then gets executed printing the error message
  • we would expect line-7 to be the next one, but here the Python interpreter recognizes that this is a return statement and it is presently inside a try-except-finally block.
  • So before executing the return statement, the finally block gets executed

2 quirks of finally block

To summarize what we have seen so far

  • The finally block is executed before handling any uncaught exceptions &
  • In case the try-except-finally is inside of a function, the finally block gets executed before any return statement is executed

Alright, now that we have learned the behavior of finally blocks, the next natural question that will pop into our heads is “In what kind of situations are these behaviors useful?

When to use the finally block

The finally block is used whenever we wish to execute some cleanup code before exiting.

try:
    # code that might raise an exception
except:
    # alternate code that will be executed when the code in the try clause is not executed
finally:
    # clean up code to close files, connections etc that might have been opened in the try block

Let us have a look at an example that depicts this use-case!

try:
    my_file = open('TextFile.txt', 'w')
    print("Opened TextFile")
    my_file.writelines("Some data")
    x = 1/0
except ZeroDivisionError:
    print("Error: Invalid input, you cannot divide a number by 0.")
finally:
    my_file.close()
    print("Closed TextFile")

print("Exiting...")

OUTPUT

Opened TextFile
Error: Invalid input, you cannot divide a number by 0.
Closed TextFile
Exiting..

Here

  • we opened a file in the try-clause
  • ran into an exception while the file is still open
  • the finally-clause closed the file for us

Yes, this can also be accomplished using the “with statement” in Python, but this example was just aimed to be a learning device.

In more complicated programs using 3rd party libraries (involving databases or networks or other such I/O) we might have objects that might not support the with statement and we might need a dedicated clean-up code to de-initialize resources before exiting the program. In such situations, the finally statement is the right tool for the job!

Now that we have mastered the topic of try-except-finally, let us have another look at the table from the beginning of the article

tryHolds the code that might raise an exception
exceptHolds the code to run in-case the try block raises an error
finallyHolds the code that must be executed before leaving this try-except block

I hope everything makes sense at this point!

There is one more keyword you need to learn which goes together with try, except, and finally which is the else keyword. We have covered that in another article, I suggest that one for your next read so that you can finally master all 4 of these awesome tools!

Python: “try-except-else-finally” Usage Explained!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: Manually throw/raise an Exception using the “raise” statement

Python catch multiple exceptions

Python: Printing Exception (Error Message)

Python: “try-except-else-finally” Usage Explained!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn