Introduction
When working with exception handling, there are situations where certain code must execute regardless of whether an exception occurs or not. Examples include closing files, releasing database connections, stopping browser sessions, and cleaning up resources.
Python provides the finally statement for this purpose.
The finally block always executes after the try and except blocks, whether an exception occurs or not.
The finally statement is commonly used in:
-
File handling
-
Database operations
-
API testing
-
Automation testing
-
Resource cleanup
-
Network programming
-
Web development
In this tutorial, you will learn about the Python finally statement, syntax, practical examples, real-world use cases, common mistakes, and best practices.
What is the finally Statement?
The finally statement defines a block of code that always executes after the try block finishes.
Whether an exception occurs or not, the finally block runs.
Example
try:
print("Inside try block")
except:
print("Inside except block")
finally:
print("Inside finally block")
Output
Inside try block
Inside finally block
Since no exception occurred, the except block was skipped, but the finally block still executed.
Basic finally Syntax
Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Exception handling code
finally:
# Code that always executes
finally Without Exceptions
Example
try:
result = 100 / 5
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution completed")
Output
20.0
Execution completed
finally With Exceptions
Example
try:
result = 100 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Execution completed")
Output
Division by zero
Execution completed
The finally block executes even when an exception occurs.
Understanding Program Flow
Example
try:
print("Step 1")
except:
print("Step 2")
finally:
print("Step 3")
Output
Step 1
Step 3
Using try, except, else, and finally Together
Example
try:
result = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Success")
finally:
print("Finished")
Output
Success
Finished
finally in File Handling
One of the most common uses of finally is closing files.
Example
try:
file = open("sample.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found")
finally:
print("Closing file")
Output
Closing file
The cleanup code executes regardless of success or failure.
Closing a File Safely
Example
file = None
try:
file = open("sample.txt")
except FileNotFoundError:
print("File not found")
finally:
if file:
file.close()
print("File closed")
finally with User Input
Example
try:
age = int(input("Enter age: "))
print(age)
except ValueError:
print("Invalid input")
finally:
print("Input operation completed")
finally with Lists
Example
try:
numbers = [10, 20, 30]
print(numbers[5])
except IndexError:
print("Index error")
finally:
print("List operation completed")
Output
Index error
List operation completed
finally with Dictionaries
Example
try:
student = {
"name": "John"
}
print(student["age"])
except KeyError:
print("Key not found")
finally:
print("Dictionary operation completed")
Output
Key not found
Dictionary operation completed
finally in Automation Testing
The finally block is widely used in automation frameworks to perform cleanup activities.
Example: Selenium Browser Cleanup
try:
print("Executing test case")
except Exception:
print("Test failed")
finally:
print("Closing browser")
Output
Executing test case
Closing browser
Example: API Test Cleanup
try:
print("Sending API request")
except Exception:
print("API error")
finally:
print("Generating report")
Output
Sending API request
Generating report
Example: Database Connection Cleanup
try:
print("Connecting to database")
except Exception:
print("Connection failed")
finally:
print("Closing connection")
Output
Connecting to database
Closing connection
Real-World Example: ATM Transaction
Example
try:
amount = int(input("Enter amount: "))
print("Processing transaction")
except ValueError:
print("Invalid amount")
finally:
print("Transaction session ended")
Real-World Example: Student Registration
Example
try:
roll_number = int(input("Enter roll number: "))
except ValueError:
print("Invalid roll number")
finally:
print("Registration process completed")
Real-World Example: Product Order Processing
Example
try:
quantity = int(input("Enter quantity: "))
except ValueError:
print("Invalid quantity")
finally:
print("Order processing completed")
finally Executes Even with return
Example
def demo():
try:
return "Inside try"
finally:
print("Inside finally")
print(demo())
Output
Inside finally
Inside try
The finally block executes before the function returns.
Difference Between else and finally
| Feature | else | finally |
|---|---|---|
| Executes on Success | Yes | Yes |
| Executes on Exception | No | Yes |
| Used for Cleanup | No | Yes |
| Executes Always | No | Yes |
Common Mistakes Beginners Make
Expecting finally to Run Only on Errors
Incorrect Understanding
Many beginners assume finally runs only when exceptions occur.
Reality
It always executes.
Using finally Instead of except
Incorrect
try:
result = 10 / 0
finally:
print("Error handled")
finally does not handle exceptions.
Writing Error Handling Code in finally
Avoid
finally:
print("Division by zero")
Error handling should be placed inside except.
Ignoring Resource Cleanup
Many beginners forget to close files or connections.
Using finally helps prevent resource leaks.
Best Practices
Use finally for Cleanup Operations
finally:
file.close()
Keep finally Blocks Simple
Only place cleanup-related code inside the finally block.
Avoid Business Logic in finally
Do not place application logic inside cleanup sections.
Release Resources Properly
Close files, database connections, and browser sessions.
Use Meaningful Messages
finally:
print("Process completed")
Advantages of finally Statements
-
Executes regardless of exceptions
-
Ensures resource cleanup
-
Improves program reliability
-
Prevents resource leaks
-
Essential for automation frameworks
Limitations of finally Statements
-
Does not handle exceptions
-
Can make code harder to read if overused
-
Should not contain complex business logic
Conclusion
The finally statement is an important part of Python exception handling. It guarantees that specific code executes regardless of whether an exception occurs.
It is primarily used for cleanup operations such as closing files, terminating browser sessions, releasing database connections, and freeing resources.
Whether you’re building applications, processing files, testing APIs, or developing automation frameworks, the finally statement helps create reliable and maintainable code.
Mastering the finally statement is an important step before learning custom exceptions, exception hierarchies, context managers, and advanced resource management techniques.
Frequently Asked Questions (FAQs)
What is the finally statement in Python?
The finally block contains code that always executes after the try block.
try:
print("Hello")
finally:
print("Finished")
Does finally execute if an exception occurs?
Yes.
The finally block always executes.
Does finally execute if no exception occurs?
Yes.
It executes regardless of success or failure.
What is the primary use of finally?
Cleanup operations such as:
-
Closing files
-
Closing database connections
-
Releasing resources
-
Closing browser sessions
Can finally be used without except?
Yes.
try:
print("Hello")
finally:
print("Finished")
This is valid Python syntax.
Key Takeaways
-
The
finallyblock always executes. -
It runs whether an exception occurs or not.
-
It is mainly used for cleanup operations.
-
Files and database connections are commonly closed in
finally. -
finallydoes not replaceexcept. -
Error handling belongs in
except. -
Cleanup logic belongs in
finally. -
finallyexecutes even when a function returns. -
It improves reliability and resource management.
-
Understanding
finallyis essential before learning context managers (withstatement) and advanced exception handling.
