Introduction and Lesson Overview

Welcome back! Today, our focus will be on the finally block, which concludes Python's three-part exception handling methodology. Exception handling protects our program from failing when unexpected errors occur. The finally block can be likened to a diligent worker who secures the office during emergencies.

Our objective is to comprehend the function of finally and its role in exception handling. We'll use real-life analogies and interactive code examples to achieve this. Shall we begin?

Understanding the finally Block

The finally block is an integral part of Python's exception-handling mechanism. It protects crucial code that needs to be executed irrespective of any exceptions. Imagine it as a responsible worker who, during sudden emergencies, ensures the electricity is off and the office door is locked.

Syntax Overview

In Python's exception handling sequence, the finally block follows the try and except blocks. It begins with the finally keyword and a colon, which is followed by indented lines of code that get executed unconditionally:

try:
    # Risky operation
except ValueError:
    # Handle error
finally:
    # Always execute this block at the end

In this code snippet, the finally block executes before the program concludes, regardless of any exceptions. This block will execute after the risky operation and exception handling, if any.

Examples and Explanation

Consider a program that attempts to divide 10 by 0, thereby triggering a ZeroDivisionError. Observe how the finally block executes, despite the exception:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Oops! Division by zero!")
finally:
    print("Always executed.")

Even when an exception occurs, finally ensures that essential clean-up tasks are completed.

Now, let's try dividing 10 by 5:

try:
    result = 10 / 5
    print("Result is:", result)
except ZeroDivisionError:
    print("Oops! Dividing by zero.")
finally:
    print("Always executed.")

As you can observe, the finally block executes even when no exception arises!

Errors and Troubleshooting
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal