Do You Really Understand Try & Finally in Python?

In python, try and except blocks are often used by programmers for handling any exception or unhappy scenarios. Finally clause is very under appreciated & can be better utilised. Let us check out how final-block works.

Aravind Ramalingam
Apr 18 · 3 min read

Deep dive

Example 1:

# Both the try & final blocks have print statements and function returns value from final-block
def example_1():
try:
val = 1
print(f"Print: Try Block - {val}")
finally:
val = val + 1
print(f"Print: Finally Block - {val}")
return f"Return: Finally Block - {val}"

example_1()

Example 2:

# The try block has return statement & final block has only print statement
def example_2():
try:
val = 1
print(f"Print: Try Block - {val}")
return f"Return: Try Block - {val}"
finally:
val = val + 1
print(f"Print: Finally Block - {val}")

example_2()

Example 3:

# Both the try & final blocks have return statements
def example_3():
try:
val = 1
print(f"Print: Try Block - {val}")
return f"Return: Try Block - {val}"
finally:
val = val + 1
print(f"Print: Finally Block - {val}")
return f"Return: Finally Block - {val}"

example_3()

Take Away

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

Analytics Vidhya

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

Aravind Ramalingam

Written by

Sharing my journey with Python, Computer Vision, Deep Learning and everything related to it. This includes the good, the bad and the ugly.

Analytics Vidhya

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