Python’s try…finally Statement

This little guy is often overlooked but can save you from some serious headaches down the line.

So what exactly does it do? Well, let me put it this way: when you use a try block to catch an exception (like if you’re trying to divide by zero), and then include a finally block, that code will always run whether or not there was an error in the first place.

Here’s an example:

# This script uses a try block to catch an exception and includes a finally block to ensure that certain code is always executed, regardless of whether or not an error occurs.

# First, we prompt the user to enter two numbers and convert them to integers.
try:
    x = int(input("Enter a number: ")) # prompts user to enter a number and converts it to an integer
    y = int(input("Enter another number: ")) # prompts user to enter another number and converts it to an integer

# If the user enters a non-integer value, a ValueError will be raised and the except block will be executed.
except ValueError:
    print("Invalid input!") # prints a message to inform the user of the invalid input

# Regardless of whether or not an error occurs, the code in the finally block will always be executed.
finally:
    print("This is always executed.") # prints a message to inform the user that this code is always executed

In this example, we’re using the try block to catch any potential errors that might occur when trying to convert user input into integers. If there’s an error (like if they enter a string instead of a number), then the except block will handle it and print “Invalid input!” But regardless of whether or not there was an error, the finally block will always execute and print “This is always executed.”

So why use this statement? Well, for one thing, it’s great for cleanup actions. Let’s say you have a file that needs to be opened in order to perform some operation on its contents but if there’s an error during the operation, you want to make sure that the file is properly closed before exiting the program. This is where finally comes in handy:

# This script is used to demonstrate the use of the 'finally' statement in python.
# The 'finally' statement is used to ensure that a certain block of code is executed, regardless of whether an exception is raised or not.

# First, we import the necessary module 'os' to handle file operations.
import os

# Next, we define a function 'open_file' that takes in a file name as a parameter.
def open_file(file_name):
    try:
        # We use the 'with' statement to open the file in read mode and assign it to the variable 'f'.
        with open(file_name, 'r') as f:
            # Within the 'with' statement, we can perform any operations on the file.
            # In this case, we will simply print out the contents of the file.
            print(f.read())
    # If an exception is raised during the execution of the 'with' statement, the code within the 'except' block will be executed.
    except:
        # We print out a message indicating that an error has occurred.
        print("An error occurred while trying to read the file.")
    # The 'finally' statement ensures that the file is closed, regardless of whether an exception is raised or not.
    finally:
        # We use the 'close' method to close the file.
        f.close()

# We call the 'open_file' function and pass in the name of the file we want to open.
open_file('myfile.txt')

# Output:
# Contents of myfile.txt will be printed if no error occurs.
# If an error occurs, the message "An error occurred while trying to read the file." will be printed.
# In both cases, the file will be closed after the execution of the 'finally' statement.

In this example, we’re using a context manager (the `with` statement) to automatically close the file when it goes out of scope but if there’s an error during the operation, the finally block will still execute and make sure that the file is properly closed before exiting.

The try…finally statement: your new best friend in Python error handling. Give it a shot next time you need to handle some tricky code I promise it won’t let you down.

SICORPS