Master Python Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

finally in Python

Learn how to use the finally block to execute code whether an exception occurs or not.

What is finally?

The finally block is used with try and except.

The code inside the finally block is executed whether an exception occurs or not.

Simple Definition: The finally block always executes after the try and except blocks.

finally Flow

try Block

Python executes the main code.

↓
No Exception

Program continues normally.

Exception Occurs

Matching except block handles the error.

↓
finally Block

The finally block executes in both situations.

Basic Syntax

try:

    # code

except:

    # handle exception

finally:

    # code that always executes

The finally block is written after the except block.

Simple Example

try:

    number = 10 / 2

    print(number)

except ZeroDivisionError:

    print("Cannot divide by zero")

finally:

    print("Finally block executed")

Output:

5.0
Finally block executed

No exception occurs, but the finally block still executes.

finally When Exception Occurs

try:

    number = 10 / 0

    print(number)

except ZeroDivisionError:

    print("Cannot divide by zero")

finally:

    print("Finally block executed")

Output:

Cannot divide by zero
Finally block executed

Even though an exception occurs, the finally block executes.

When No Exception Occurs

try:

    print("Program started")

except Exception:

    print("An error occurred")

finally:

    print("Program finished")

Output:

Program started
Program finished

When an Exception Occurs

try:

    result = 10 / 0

except ZeroDivisionError:

    print("Division by zero")

finally:

    print("Execution completed")

Output:

Division by zero
Execution completed

finally with User Input

try:

    number = int(
        input("Enter a number: ")
    )

    print("Number:", number)

except ValueError:

    print("Invalid number")

finally:

    print("Input processing completed")

The finally block runs whether the user enters a valid or invalid value.

Practical Use of finally

The finally block is commonly used when something must be completed after an operation.

File Handling

Used when a file operation must be completed or cleaned up.

Database

Useful for cleanup after database operations.

Resources

Useful when resources need to be released.

Example: File Handling

try:

    file = open("students.txt", "r")

    data = file.read()

    print(data)

except FileNotFoundError:

    print("File not found")

finally:

    print("File operation completed")

The finally block executes after the file operation.

try, except and finally Together

try:

    number = int(
        input("Enter a number: ")
    )

    result = 100 / number

    print("Result:", result)

except ValueError:

    print("Invalid number")

except ZeroDivisionError:

    print("Cannot divide by zero")

finally:

    print("Program completed")

Here, multiple exceptions can be handled and the finally block executes at the end.

Important Points

  • The finally block executes whether an exception occurs or not.
  • It is normally used with try and except.
  • It is useful for cleanup operations.
  • It executes after the try and except blocks.

Best Practices

Cleanup Code

Use finally for code that should run after the operation.

Keep It Simple

Keep finally focused on cleanup or completion tasks.

Handle Errors

Use except blocks for specific errors before finally.

Common Mistakes

  • Forgetting that finally executes even when an exception occurs.
  • Putting unrelated code inside the finally block.
  • Using finally when simple sequential code is enough.
  • Not understanding the order of try, except and finally.

Practice Programs

  1. Create a program using try, except and finally.
  2. Handle division by zero and execute a finally block.
  3. Take user input and use finally after handling ValueError.
  4. Create a file handling example using finally.
  5. Create a calculator that uses multiple exceptions and a finally block.

Summary

The finally block is used to execute code after a try and except block. It executes whether an exception occurs or not. It is especially useful for cleanup operations and tasks that must be completed after an operation.