How to use Python try…except…finally
Summary: In this article, I will demonstrate how to use Python try
…except
…finally statement.
Introduction to Python try…catch…finally statement
List most programming languages, Python supports catching and handling exceptions during runtime. The try
… except
is the most common tool. It allows you to catch one or more exceptions in the try
clause and handle each of them in the except
clauses.-
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
try
…except
statement.
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.