How to use Python try…except…finally

Jack Dong
Analytics Vidhya
Published in
3 min readSep 26, 2021

--

Summary: In this article, I will demonstrate how to use Python tryexcept…finally statement.

Introduction to Python try…catch…finally statement

List most programming languages, Python supports catching and handling exceptions during runtime. The tryexcept is the most common tool. It allows you to catch one or more exceptions in the tryclause and handle each of them in the exceptclauses.-

The statement also has an optional clause called finally:

  • The finally clause always executes whether an exception occurs or not. And it executes after the tryexceptstatement.
try:
# code that might cause exceptions
except:
# code that handle exceptions
finally:
# code that always executes

Python try … finally statement

The catch clause is also optional, so you can use it like this:

try:
# code that might cause exceptions
finally:
# code that always executes

Typically, you might use this statement when you cannot handle the exception but you want to release some external resources. For example, you want to close database connection that has been built.

Python try … else statement

--

--

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

No responses yet