Finally

Python · Exception Handling

Theory

The finally block runs no matter how the try statement ends: after a successful try, after an except handled an error, when an exception was not caught at all, and even when the try or except executes return, break or continue. That makes it the right place for cleanup that must always happen.

In the example, 10 / 0 is caught and prints 'Error', then finally prints 'Cleanup complete'. If the error had not been caught, finally would still run first and then the exception would continue to the caller. Typical cleanup includes closing files or database connections, releasing locks and deleting temporary files. For files and many connections, the with statement provides the same guarantee automatically, which is why you see with more often than finally in modern code.

Why we use it

Resources like files, connections and locks must be released even when something fails, or they leak and cause problems later. finally guarantees the cleanup code runs on every path.

When to use it

Use finally for cleanup that must always happen, especially for resources without a context manager. When a with statement is available (files, many DB connections), prefer it - it does the same job more neatly.

How it works

  1. Run the try block
  2. Did an exception occur? Yes: Look for a matching except. No: Skip the except blocks.
  3. Was the exception handled? Yes: Run except, then finally. No: Run finally, then it propagates.
  4. Run finally (always)
  5. Continue, or propagate the unhandled error

Syntax

try:
    ...
finally:
    cleanup()

Example

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error")
finally:
    print("Cleanup complete")

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic