Signup/Sign In

Python finally

The finally code block is also a part of exception handling. When we handle exception using the try and except block, we can include a finally block at the end. The finally block is always executed, so it is generally used for doing the concluding tasks like closing file resources or closing database connection or may be ending the program execution with a delightful message.


finally block with/without Exception Handling

If in your code, the except block is unable to catch the exception and the exception message gets printed on the console, which interrupts code execution, still the finally block will get executed.

Let's take an example:

Try to run the above code for two different values:

  1. Enter some integer value as numerator and provide 0 value for denominator. Following will be the output:

    You have divided a number by zero, which is not allowed. Code execution Wrap up! Will this get printed?

    As we have handled the ZeroDivisionError exception class hence first the except block gets executed, then the finally block and then the rest of the code.

  2. Now, some integer value as numerator and provide some string value for denominator. Following will be the output:

    Code execution Wrap up! Traceback (most recent call last): File "main.py", line 4, in <module> b = int(input("Enter denominator number: ")) ValueError: invalid literal for int() with base 10: 'dsw'

    As we have not handled the ValueError exception, hence our code will stop execution, exception will be thrown, but still the code in the finally block gets executed.


Exception in except block

We use the except block along with try block to handle exceptions, but what if an exception occurred inside the except block. Well the finally block will still get executed.

# try block
try:
    a = 10
    b = 0
    print("Result of Division: " + str(a/b))
# except block handling division by zero
except(ZeroDivisionError):
    print("Result of Division: " + str(a/b))
finally:
    print("Code execution Wrap up!")

Code execution Wrap up! Traceback (most recent call last): File "main.py", line 4, in <module> print("Result of Division: " + str(a/b)) ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "main.py", line 7, in <module> print("Result of Division: " + str(a/b)) ZeroDivisionError: division by zero

Clearly the finally block was the first to be printed on the console follwed by the first exception message and then the second exception message.