We use try-except blocks to perform exception handling in Python. This article discusses how you can use the Python finally block along with try-except statements for resource handling and better execution of the program.
Exception Handling in Python
Exceptions cause a program to terminate abruptly. Whenever an exception occurs, the execution of the program is terminated and the control is transferred to the exception handler. Then, the interpreter prints the error message. You can observe this in the following program.
input_string=input("Please input a number:")
input_number=int(input_string)
square=input_number**2
print("The square of {} is {}.".format(input_number,square))
Output:
ValueError Traceback (most recent call last)
/tmp/ipykernel_40005/2290798086.py in <module>
1 input_string=input("Please input a number:")
----> 2 input_number=int(input_string)
3 square=input_number**2
4 print("The square of {} is {}.".format(input_number,square))
ValueError: invalid literal for int() with base 10: 'PFB'
In the above example, the program asks the user for giving a number as input. It then calculates the square of the number and prints it. If we pass a string such as “PFB” to the program, it cannot be converted into a number. Hence, the program will run into a Python ValueError exception and the execution stops instantly.
We can use Python try-except blocks to terminate the program smoothly when an exception occurs in a program. For this, we can execute the code in the try block and handle all the exceptions in the except block. Here, the try block is executed normally. If the program runs into an error, the execution is diverted to the except block where we can handle the exception. You can observe this in the following example.
try:
input_string=input("Please input a number:")
input_number=int(input_string)
square=input_number**2
print("The square of {} is {}.".format(input_number,square))
except ValueError:
print("Please input a number not a string.")
Output:
Please input a number:PFB
Please input a number not a string.
In the above example, we have used the try-except block to handle the error. As the ValueError exception is raised by the int() function, the except block catches it. Then, we print a message that the user should input a number and not a string. After that, the execution of the program is stopped smoothly.
If no error occurs in the try block, the except block is not executed. For example, if we input a number into the program, it will execute normally and will print the square of the input number. You can observe this in the following example.
try:
input_string=input("Please input a number:")
input_number=int(input_string)
square=input_number**2
print("The square of {} is {}.".format(input_number,square))
except ValueError:
print("Please input a number not a string.")
Output:
Please input a number:10
The square of 10 is 100.
When we use try-except blocks to handle exceptions, the statements after the error are never executed once the error is raised in the try block.
Now, if we want to perform some task like freeing a port or closing a file, we can’t do it once the program runs into an error. This is where the finally block comes into play. We use the finally block to execute a code whether the exception is raised or not. Let us discuss how to implement a program using the finally block in Python.
The Finally Block in Python
We use the finally block to mandatorily execute a code in Python. The syntax for using the finally block is as follows.
try:
#do something
except:
#do something once error occurs
finally:
#you must do it.
In the above syntax, the statements in the try block are executed normally. If the program doesn’t run into any error, the code in the finally block is executed after the try block. You can observe this in the following example.
try:
input_string=input("Please input a number:")
input_number=int(input_string)
square=input_number**2
print("The square of {} is {}.".format(input_number,square))
except ValueError:
print("Please input a number not a string.")
finally:
print("This will always be executed.")
Output:
Please input a number:11
The square of 11 is 121.
This will always be executed.
If the code in the try block runs into an error, the code in the except block is executed to handle the error. After that, the code in the finally block is executed as shown below.
try:
input_string=input("Please input a number:")
input_number=int(input_string)
square=input_number**2
print("The square of {} is {}.".format(input_number,square))
except ValueError:
print("Please input a number not a string.")
finally:
print("This will always be executed.")
Output:
Please input a number:PFB
Please input a number not a string.
This will always be executed.
Even if the except block does not handle the error, the code in the finally block will be executed for sure. You can observe this in the following example.
try:
input_string=input("Please input a number:")
input_number=int(input_string)
square=input_string**2
print("The square of {} is {}.".format(input_number,square))
except ValueError:
print("Please input a number not a string.")
finally:
print("This will always be executed.")
Output:
Please input a number:10
This will always be executed.
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
In this example, the program runs into a Python TypeError exception. As the except block only handles the ValueError exception, the program runs an error when the TypeError exception occurs. However, you can observe that the finally block is executed before the program runs into error.
When to Use Finally Block in Python?
While coding in Python, there are many instances where we need to compulsorily execute some statements. Following are the situations where you can use the Python finally block.
- When we write some data into a file, it’s not saved until the file is closed. Now, when the program runs into an error, it is highly likely that the file will not be closed before the execution of the code in the except block. You can use the Python finally block to close a file using the close() method in the finally block. In this way, you can close the file whether or not the program runs into any error. This will help you avert any loss of data.
- We can also use the finally block to close connections and free network ports while implementing socket programming in Python.
- In any situation where we must compulsorily execute some statements, you can use the finally block after the try-except statements.
Conclusion
In this article, we discussed how to implement the finally block in Python. We also discussed the use cases of the Python finally block. To learn more about Python programming, you can read this article on how to terminate a Python program. You might also like this article on how to create a dictionary from a string in Python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.