Finally in Python | Try Except Finally Python
So far, you will have noticed that when an exception raises within try block in a program, the rest of statements within try block does not execute and the control of execution directly gets passed to the subsequent except block.
However, there are such certain statements in a program that need to be executed regardless of whether the exception has occurred or not. For this, Python provides a keyword named “finally“.
A finally clause in Python is a block of code that always gets executed regardless of whether an exception has occurred in the try block or not.
It plays as an important exception handler in exception handling mechanism. The code placed in the finally block is always executed no matter what happens in the try or except blocks.
Even if an uncaught or unhandled exception propagates up the call stack, the finally clause will still execute before the program ends. However, the finally block is an optional with the try block but can be very useful in certain situations.
We can use the finally block to ensure that external resources such as files, network connections, or database connections, are properly freed up or closed. It prevents the resources leaks and maintains them in a consistent state. It can also be useful for finalizing operations.
Let’s consider an example to illustrate the usage of the “finally” block in Python:
try:
file = open("example.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found!")
else:
print("File content: ", data)
finally:
file.close() # File closure in the finally block
print("File closed (if open) successfully")
In this example, we have performed the file handling operation, such as opening and reading a file within the try block. If the file does not exist during the program execution, a FileNotFoundError exception occurs and the except block handles it.
Regardless of whether an exception has raised or not, the “finally” block ensures that the file is closed, and displays a message indicating that file is closed successfully. Thus, the finally block guarantees proper resource management.
Syntax to Define Try Except Finally in Python
The general syntax to define try except else finally block in Python is as follows:
try:
statement(s) # Code block that may raise an exception
except ExceptionType1:
statement(s) # Exception handling code
except ExceptionType2:
statement(s) # Exception handling code
else:
statement(s) # Code block executes only if no exception is raised in the try block
finally:
statement(s) # Code that will execute whether an exception occurred or not
In the above syntax,
- try: This block contains the code where an exception might occur.
- except ExceptionType1: If ExceptionType1 (or a subclass of it) is raised during the execution of the try block, the code within this except block will be executed to handle that specific exception type.
- except ExceptionType2: Similarly, if ExceptionType2 (or its subclass) is raised, the code within this except block will handle that specific exception type.
- else: This block executes only if no exceptions are raised in the try block. It contains the code that runs when no exceptions occur.
- finally: Irrespective of whether an exception is raised or not, the code within this block always executes. It’s primarily used for cleanup operations or tasks that need to be performed regardless of exceptions.
Control Flow of Try-Except-Finally Block in Python
The code within the finally block always gets executed regardless of whether the exception has occurred within the try block or not. If the raised exception matches with the except block, the first except block is executed, and then proceeds to execute the finally block.
On the other hand, if an exception is raised within the try block and there’s no matching except block, Python still executes the finally block before terminating the program due to the unhandled exception.
The diagrammatic representation of working of Python try-except-finally block has been shown in the below figure.
Example Program based on Try Except Finally Block
Let’s take some important example programs to clear more concepts based on the try except else finally block in Python.
Example 1: try-finally combination
try:
x = int(input("Enter your first number: "))
y = int(input("Enter your second number: "))
result = x / y
print("Result = ", result)
finally:
print("Finally block always gets executed!")
Output:
First run:
Enter your first number: 20
Enter your second number: 5
Result = 4.0
Finally block always gets executed!
Second run:
Enter your first number: 30
Enter your second number: 0
Finally block always gets executed!
ZeroDivisionError: division by zero
As you can see that the finally block in Python executes its code no matter what happens within the try block. Whether an exception occurs or not, the code within the finally block will always be executed.
Example 2: try-except-finally combination
try:
# Attempting some code that might raise an exception
result = 40 / 0 # This operation will raise a ZeroDivisionError
print("Result:", result) # This line won't be executed due to the error
except ZeroDivisionError:
# Handling the specific exception (ZeroDivisionError in this case)
print("Error: Division by zero occurred")
finally:
# This block will always execute, regardless of whether an exception occurred or not
print("Finally block gets executed!")
Output:
Error: Division by zero occurred
Finally block gets executed!
In this example, we have performed a division operation that will raise a ZeroDivisionError exception within the try block. The except block catches this specific type of exception and handles it by printing an error message on the console.
After the execution of except block, the finally block executes, irrespective of whether an exception occurs in the “try” block and handles or not by “except” block.
Example 3: try-except-else-finally block combination
try:
# Attempting some code that might raise an exception
result = int(input("Enter a number: "))
print("You entered:", result)
except ValueError:
# Handling the exception if the entered value is not a valid integer
print("Error: Please enter a valid integer")
else:
# This block executes only if no exception (ValueError) occurs in the try block
print("No exception occurred. Thank you for entering a valid number!")
finally:
# This block always executes, regardless of exceptions, for cleanup or finalization
print("Finally block: Execution completed")
Output:
First run:
Enter a number: 20
You entered: 20
No exception occurred. Thank you for entering a valid number!
Finally block: Execution completed
Second run:
Enter a number: good
Error: Please enter a valid integer
Finally block: Execution completed
In this example, within the try block, we have taken an input from the user and converted it into an integer. If the user enters a value that cannot be converted to an integer, it will raise a ValueError exception within the try block. The except block handles this exception by displaying an error message.
If no exception occurs (i.e., the user enters a valid integer), the else block executes and shows a message indicating no exceptions. The finally block, regardless of whether an exception occurred or not, gets executed.
Example 4:
try:
print("One")
print("Two")
except(Exception):
print(10/0)
finally:
print("Three")
print("Four")
Output:
One
Two
Three
Four
In this example, an exception has occurred in the except block, not inside try block. Therefore, except block will not execute and the control will directly go to execute finally block. This is because exception that occurred in the except block is not part of the try block.
Example 5:
try:
print("One")
print(20/0)
print("Two")
except(Exception):
print(10/0)
finally:
print("Three")
print("Four")
Output:
One
Three
ZeroDivisionError: division by zero
In the above code, a ZeroDivisionError occurs within the try block. The program control is transferred to the appropriate except block to handle this exception, but another ZeroDivisionError exception also occurs within the except block. Therefore, it will disrupt the normal exception handling process.
When another exception arises while handling the initial exception (in this case, within the except block), Python does not terminate the program immediately. Instead, it prioritizes handling the new exception that occurs within the exception handler. If this secondary exception remains unhandled, it could lead to the program’s abnormal termination by the default exception handler.
However, before the termination of the program due to unhandled exceptions, the Python interpreter will go to execute only finally block associated with the try block.
Best Practices for Using Finally Block in Python
There are some key points that you should keep in mind while utilizing finally clause. They are as:
- A finally block is optional but at least one of the except or finally block must exist with a try.
- It must be defined at the end of the last except or else block. If we define the finally block before an except or else block, the program will generate SyntaxError.
- Unlike except block, we cannot declared multiple finally blocks with a single try block. That is there can be only one finally clause with a single try block.
- Always include a “finally” block when handling critical resources.
- Avoid performing complex operations within the “finally” block to maintain its simplicity and reliability.
- Ensure proper exception handling within the try-except blocks to minimize potential errors.
FAQs on “finally” Block
Q1. Is the “finally” block mandatory in exception handling?
No, the finally block is not mandatory in exception handling in Python, but it can be exceptionally useful in certain scenarios, such as to handle cleanup or finalization tasks, like closing files or releasing resources, regardless of whether an exception is raised or not.
Q2. Can the “finally” block be used without the try-except block?
Yes, we can use the finally block without the try-except block. It’s not compulsory for the finally block to be coupled with a try-except clause. Look at the below example code.
def perform_operation():
try:
result = 10 / 2
print("Result of operation:", result)
finally:
# Code within the finally block will execute even without a try-except block
print("Finally block gets executed regardless of exceptions")
# Function call
perform_operation()
Output:
Result of operation: 5.0
Finally block gets executed regardless of exceptions
Q3. What happens if an exception occurs in the “finally” block itself?
Let’s understand it with the help of an example.
def funct():
try:
print("One")
print(20/0)
print("Two")
except(ZeroDivisionError):
print("Exception handled")
finally:
print(50/0) # Exception occurred in finally block.
print("Four")
# Function calling.
funct()
Output:
Four
One
Exception handled
ZeroDivisionError: division by zero
In this example, a ZeroDivisionError exception has occurred within the try block. Since the raised exception object is matched with the corresponding except block, the program control will immediately go to except block to handle the exception.
After the complete execution of except block, Python interpreter will go to execute finally block, but inside finally block, an exception also raised. So, the interpreter will terminate the program abruptly, displaying an error message related to this new unhandled exception.
Q4. Is there any scenario where the “finally” block might not execute in Python?
If the code within the try, except, or elsewhere in the program enters an infinite loop or hangs indefinitely, it prevents the normal execution flow. In this case, the finally block might not get a chance to execute.
In this tutorial, we have discussed finally block in Python with the help of various example programs. Hope that you will have understood the basic concept of using finally block with try-except block. Stay tuned with the next tutorial where we will learn how to create user-defined exception or custom exception in Python.
Thanks for reading!!!






