The Python, finally keyword is used along with try and except block. This block is executed irrespective of the error raised in the try block. It can used without the except block, thought the try block raise an error, the finally can be executed.
If we use finally block without the try it will raise an SyntaxError.
SyntaxFollowing is the syntax of the Python finally keyword −
finally: statementExample
Following is an basic example of the Python finally keyword −
var1 = 2 var2 = 'nine' try: print(var1//var2) except Exception as e: print("Error :",e) finally: print("Hello, Welcome to Tutorialspoints")Output
Following is the output of the above code −
Error : unsupported operand type(s) for //: 'int' and 'str' Hello, Welcome to TutorialspointsUsing finally without try block
We cannot use the finally block with out try block it will result in SyntaxError −
ExampleIn the following example we have defined the finally without try block and raised an error −
finally: print("It will result an SyntaxError")
Output
Following is the output of the above code −
File "E:\pgms\Keywords\finally.py", line 44 finally: ^^^^^^^ SyntaxError: invalid syntaxUsing finally without except block
The finally can be used without except block. The finally block is executed even there is an error raised in the try block.
ExampleHere, we have executed critical statement in the try block, thought it raised an error the finally block is executed −
try: print(1/0) finally: print("Without Except Block")
Output
Following is the output of the above code −
Without Except Block Traceback (most recent call last): File "/home/cg/root/44145/main.py", line 2, in <module> print(1/0) ZeroDivisionError: division by zeroUsing finally in files
We can also create a file and open it in different modes using try and finally. The finally block is executed irrespective of the error raised in the file.
ExampleHere, we have opened the file in the write[W] mode and performed some operations and the finally block is executed −
try: f = open("file.txt", "w") f.write("Welcome To The Tutorialspoints") finally: print ("The file is created and appended the text.") f.close()
Output
Following is the output of the above code −
The file is created and appended the text.
python_keywords.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4