Python Try Finally Tutorial – Complete Guide

Understanding exceptions and how to handle them is quintessential for every aspiring Python programmer. Akin to a skilled game player anticipating unexpected moves, proficient coders should prepare for unexpected behaviours in their code. In this tutorial, we unravel the mysteries behind Python’s try and finally clause, exploring how we can use it to make our code more robust and resilient. Whether you’re a rookie just setting out or an experienced coder looking to sharpen your skills, this tutorial promises to be an enlightening journey.

What is Python Try Finally?

Python provides several built-in structures for exception handling, with try and finally being two such key components. Think of them as onboard airbags and seatbelts in your game vehicle, designed to protect you when unexpected incidents occur.

The try clause lets you test a block of code for errors, while the finally clause permits you to execute tasks, irrespective of whether an exception was encountered in the try block or not. Picture this like a game character’s skill that always activates, regardless of the set gameplay. Indeed, a handy tool in the hands of a smart programmer!

Python’s try and finally statements allow your code to fail gracefully when things go awry, rather than breaking down in a catastrophic manner. Learning how to use them effectively equips you with skills to write more robust, error-resistant scripts. Not unlike a skillful gamer manoeuvring through unpredictable terrain, understanding try and finally helps you navigate your coding journey more efficiently.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Coding Basics of Try – Finally Clause

The fundamental syntax of try and finally in Python is as follows:

try:
   // your code here
finally:
   // your code here

Let’s delve right into some practical examples to illustrate the utility of the try, finally clause in Python.

Case 1: No Exception Raised

Let’s see what happens when there’s no exception raised in the try block:

try:
    print("Hello from Zenva!")
finally:
    print("Finally clause executed!")

Here, even though no exception is raised, the finally clause is still executed.

Case 2: Exception Raised but not Handled

If an exception occurs in the try block and is not handled, the finally block is still executed:

try:
    div = 5 / 0  # ZeroDivisionError raised here
finally:
    print("Finally clause executed!")

Despite the ZeroDivisionError exception, the finally block executes as expected.

Case 3: Exception Raised and Handled

How about when an exception is raised in the try block and is duly handled? Let’s check it out:

try:
    div = 5 / 0  # ZeroDivisionError raised here
except ZeroDivisionError:
    print("Divide by zero error caught!")
finally:
    print("Finally clause executed!")

Here, the ZeroDivisionError exception is caught and handled, but the finally clause executes nonetheless.

Case 4: Exception Raised in Finally Block

In the unlikely situation where an exception is raised within the finally block itself, the program will break:

try:
    print("Hello from Zenva!")
finally:
    div = 5 / 0  # ZeroDivisionError raised here

In this case, we don’t have an except clause to handle the exception raised within finally. Consequently, the program terminates abruptly.

Case 5: Using ‘finally’ with Files

Working with files is routine in Python programming. Let’s have a look at how finally can come in handy in this context:

try:
    fp = open("zenva.txt", "r")
    content = fp.read()
    print(content)
finally:
    fp.close()
    print("File closed!")

In this scenario, irrespective of whether an exception occurred while reading the file, the finally clause ensures that the file is closed, thereby preventing potential leaks.

Case 6: Using ‘finally’ with Databases

Finally clause becomes especially useful when dealing with databases. Let’s take a look:

try:
    db_conn = DB_Connect('MyDB')  # hypothetical DB_Connect class
    data = db_conn.fetch_data() 
    
except DB_Exception as e:
    print('Exception: ', str(e))
    
finally:
    db_conn.close()
    print("Database connection closed!")

Here, whether a database operation is successful or raises an exception, the finally clause makes sure to close the database connection.

Case 7: Nested Try-Finally Blocks

You can wrap the try - except - finally block in another try - finally block:

try:
    try:
        div = 5 / 0 
    except ZeroDivisionError:
        print("Caught divide by zero error!")
    finally:
        print("Inner finally block!")
finally:
    print("Outer finally block!")

This illustrates how finally ensures that cleanup actions are done, regardless of the chain of exceptions and nested blocks.

In conclusion, the Python try - finally statement is a powerful construct to add resilience and stability to your code. Grasping this concept is like perfecting a crucial game strategy, the right move at the right time can dramatically affect the outcomes. As we journey together through Python programming, these essential tools and concepts will prove indispensable.

Where to Go Next?

Having grasped the basics of Python’s try and finally statements, you might be pondering your next steps. Fear not because the journey of coding, similar to a well-plotted game, is filled with never-ending levels. At Zenva, we guide you through these levels, empowering you to master the game of coding. So, where should you head next?

We recommend our Python Mini-Degree. It’s a comprehensive collection of courses focused on Python programming, meticulously designed not only to enhance your understanding but also to equip you with practical skills. This Mini-Degree covers coding basics, algorithms, object-oriented programming, game development, and app development, thereby offering a holistic learning experience.

Like a diverse gaming arena, Python finds its footprint across various sectors, from data science and robotics to game development. By completing our Python Mini-Degree, you can build a varied portfolio of Python projects and acquire skills that are sought-after in today’s job market. The flexibility of our online courses means you can learn at your pace, whenever or wherever you are. The icing on the cake is our experienced and certified instructors who are ardent about teaching and programming.

For those who wish to explore a wider range of topics, we recommend you to check out our wide collection of Python courses. These courses cover a broad range of Python-related topics and are a perfect way to extend your learning adventure beyond this tutorial.

Conclusion

Unmasking the Python’s try and finally clause isn’t just about mastering a syntax or a programming construct. It’s akin to unlocking a crucial power-up in a game, empowering you to tackle unexpected obstacles with finesse. The capability to handle exceptions makes your code more robust, and your Python programming journey more rewarding.

At Zenva, we place in your hands the controls to guide your learning adventure. As you venture deeper into the exciting world of Python, we remain your steadfast companion, guiding you on every twist and turn. With our Python Mini-Degree, we offer you a comprehensive platform to learn, create and master Python. Remember, in the realm of coding, there is always a new level to conquer. Keep coding, keep learning, keep conquering!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.