Python Tutorial @ Home

Python Exception Handling

Python Exception
Common Exceptions
The problem without handling exceptions
Exception handling in python
The except statement with no exception
The except statement using with exception variable
Declaring Multiple Exceptions
The try…finally block
Raising exceptions

Python Exception Handling

The try…finally block

Python provides the optional finally statement, which is used with the try statement. It is executed no matter what exception occurs and used to release the external resource. The finally block provides a guarantee of the execution.
We can use the finally block with the try block in which we can pace the necessary code, which must be executed before the try statement throws an exception.
The syntax to use the finally block is given below.

Syntax

try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

try:    
    fileptr = open("file.txt","r")      
    try:    
        #fileptr.write("Hi I am good")    #error
        #or
        temp=fileptr.read()
        print(temp)
    finally:    
        fileptr.close()    
        print("file closed")    
except:    
    print("Error")   

Output:

hello this is
file.txt file
file closed

try:    
    fileptr = open("file.txt","r")      
    try:    
        fileptr.write("Hi I am good")    #error
        #or
        #temp=fileptr.read()
        #print(temp)
    finally:    
        fileptr.close()    
        print("file closed")    
except:    
    print("Error")   

Output:

file closed
Error

Visitor Counter

0051133