Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python finally Keyword



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.

Syntax

Following is the syntax of the Python finally keyword −

finally:
   statement

Example

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 Tutorialspoints

Using finally without try block

We cannot use the finally block with out try block it will result in SyntaxError

Example

In 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 syntax

Using 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.

Example

Here, 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 zero

Using 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.

Example

Here, 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
Advertisements