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 except statement with no exception

Python provides the flexibility not to specify the name of the exception with the exception statement.

Consider the following example.

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b;    
    print("a/b = %d"%c)    
    #print("a/b = ",c)
    print("{}/{} = {}".format(a,b,c))
except:    
    print("can't divide by zero")    
else:    
    print("Hi I am else block")     

Output:
Case 1:
Enter a:10
Enter b:6
a/b = 1
10/6 = 1.6666666666666667
Hi I am else block

Case 2:
Enter a:25
Enter b:0
can’t divide by zero

The except statement using with exception variable

We can use the exception variable with the except statement. It is used by using the as keyword. this object will return the cause of the exception.
Consider the following example:

try:    
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print("a/b = %d"%c)    
    # Using exception object with the except statement  
except Exception as e:    
    print("can't divide by zero")    
    #to display system defined message
    print(e)  
else:    
    print("Hi I am else block")     

Output:
Case:1
Enter a:10
Enter b:6
a/b = 1
Hi I am else block

Case:2
Enter a:10
Enter b:0
can’t divide by zero
division by zero

Example:

try:    
    #this will throw an exception if the file doesn't exist.     
    fileptr = open("file.txt","r")    
except IOError:    
    print("File not found")    
else:    
    print("The file opened successfully")   
    temp=fileptr.read()
    print(temp) 
    fileptr.close()    

Output:(if the file is present)

The file opened successfully
hello this is
file.txt file

Output:(if the file is not present)
File not found

Important points to remember

1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will be executed if no exception is raised in the try block.
4. The statements that don’t throw the exception should be placed inside the else block.

Visitor Counter

0056683