Topics

Exeption Handling: finally

Welcome to another tutorial on Python Finally. In Python, the finally code block is also a part of exception handling. Therefore, if we want to handle exception using the try and except block, we can include a finally block at the end. It is generally used for doing the concluding task such as closing file resources or closing database connections or possibly ending the program execution with a delightful message.

 

finally block with/without Exception Handling

In the case where in your code, the except block is unable to catch the exception, and the exception message gets printed on the console, that typically interrupts the code execution, but the finally block is still executed.

Check out the example:

# try block
try:
    a = int(input("Enter numerator number: "))
    b = int(input("Enter denominator number: "))
    print("Result of Division: " + str(a/b))
# except block handling division by zero
except(ZeroDivisionError):
    print("You have divided a number by zero, which is not allowed.")
finally:
    print("Code execution Wrap up!")
    
# outside the try-except block
print("Will this get printed?")

 

Now, try to run the code for two different values:

  1. Enter some integer value as a numerator and provide a 0 value for the denominator. Check out the result below:
    Output:
You have divided a number by zero, which is not allowed.
Code execution Wrap up!
Will this get printed?

Just as we handled the ZeroDivisionError exception class, therefore, the except block gets executed first; followed by the finally block, and then the rest of the code.

 

2. Then, enter some integer value as a numerator and provide some string value for the denominator. Check out the output below:

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'

From above, we did handle the ValueError exception, therefore, our code will stop the execution, and an exception will be thrown, but the code in the finally block will still get executed.


Exception in except block

In this case, we will use the except block along with the try block to handle exceptions, however, suppose an exception occurred inside the except block. But, the finally block will get executed anyway.

# 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!")

Output:

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 

In the above example, the finally block was the first to be printed on the console, and the first exception message and lastly, the second exception message is printed.