profile

Rodrigo 🐍🚀

🐍🚀 try, except, else, and finally: explained

published3 months ago
3 min read

Hey Reader, how are you doing?

In this issue of the Mathspp Insider 🐍🚀 we will talk about the full anatomy of the try block, which means we will cover four statements: try, except, else, and finally.


Before we jump right into the action, I would like to thank our sponsor, Underfitted.
Every Friday, you'll get a short, exciting story about Artificial Intelligence that will inspire and make you smarter.
And all of this in fewer than 500 words!
Click here to subscribe.

Underfitted is written by Santiago and Every. Single. Friday. I am amused by what he shares on his newsletter.
On top of his newsletter, Santiago is now working on the Machine Learning School, a community to help people build a career in AI/ML.
If you are interested in kickstarting your career in AI/ML or learning skills that will make you more valuable for companies, e-mail me for more details or check it out for yourself!


Full anatomy of the try block

A try block can have up to four different types of statements, although the try is the only one that is mandatory:

  1. try is used to indicate the code that might fail;
  2. except is used to handle specific exceptions raised inside try;
  3. else is used to specify code that runs if there was no exception; and
  4. finally is used to specify clean-up code that runs regardless of whether we caught an exception or not.

The diagram below summarises this information.
We will now go over the four statements and see how they are used.
We will close this issue with an example usage of the four statements.

try statement

As we have seen in previous weeks, the try statement is used to indicate code that you know might fail.
Ideally, you would nest as little code as possible inside the try statement, but this also depends on the usage you make of the other statements.

except statement

The except is used to indicate what error(s) you can handle and how to handle them.
You can handle one or more errors in a single except, and you can also have multiple except statements if different errors are handled differently.

For example, consider this mock code that is trying to connect to Twitter to download the most recent image I tweeted about Python to save it in my computer.
When doing that, I might get an exception TweetHasNoImageException if my last tweet did not share an image...
I might also get an QuotaException if I exceeded my API quota and called that function too many times this month.
If I get those errors, I do not want to save any images, so I might write this:

user = twitter_api.connect(my_credentials)
try:
    tweeted_image = user.get_last_tweet().get_image()
except TweetHasNoImageException, QuotaException:
    pass

else statement

The else statement is used to define code that runs if there was not an exception.
In our example, that would be the code that saves the image in my computer, because I can only do that if I did not get an exception in the previous step:

user = twitter_api.connect(my_credentials)
try:
    tweeted_image = user.get_last_tweet().get_image()
except TweetHasNoImageException, QuotaException:
    pass
else:
    with open("tweet_image.jpg") as f:
        f.write(tweeted_image)

finally statement

The finally statement is used for clean-up that should run under all circumstances.
The clean-up code that goes under finally will run regardless of whether there was an exception or not and regardless of whether the exception was handled or not.
The finally is there to really cover your back.

In our example, regardless of whether we manage to download an image or not, we want to disconnect from the API, so we can use the statement finally for that:

user = twitter_api.connect(my_credentials)
try:
    tweeted_image = user.get_last_tweet().get_image()
except TweetHasNoImageException, QuotaException:
    pass
else:
    with open("tweet_image.jpg") as f:
        f.write(tweeted_image)
finally:
    user.disconnect()

Mix and match statements

The except, else, and finally, statements are all optional.*
You can have some and not the others.
For example, you can have a try with a lone finally, that works.
*To have an else statement you need to have an except statement too.

When doing exception handling in Python, be mindful of these three optional statements and make the best use of each one of them.
Sometimes, that means not even using them.
And that is OK.


After your feedback, I decided that I will be writing about generators and generator expressions in the upcoming week(s).
If there is anything specific you would like me to cover, reply to this e-mail to let me know!

By the way, have you used the try block recently with any of these optional statements?
I came up with this fake Twitter example to use all four statements in a reasonable way, but I would be interested in real examples from real code that make use of the many statements!
Just reply to this email with your examples!


Thanks for reading, and I'll see you next time! 👋

Rodrigo.

Rodrigo 🐍🚀

Taking your Python 🐍 skills to the next level 🚀