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

Declaring Multiple Exceptions

Python allows us to declare the multiple exceptions with the except clause. Declaring multiple exceptions is useful in cases where a try block throws multiple exceptions. The syntax is given below.

Syntax:1

try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,…<Exception n>)
#block of code

else:
#block of code

Syntax:2

try:
#block of code

except (<Exception 1>):
#block of code

except (<Exception 2>):
#block of code

except (<Exception 3>):
#block of code

else:
#block of code

try:      
    a=10/0;  
    fp=open("file1.txt","r")    
except ArithmeticError:      
    print("Arithmetic Exception")      
except IOError:      
    print("Unable to open the file")      

else:      
    print("Successfully Done")       
    print("file opened")
    fp.close()

Output:
Arithmetic Exception

try:      
    #a=10/0;  
    fp=open("file1.txt","r")    
except ArithmeticError:      
    print("Arithmetic Exception")      
except IOError:      
    print("Unable to open the file")      

else:      
    print("Successfully Done")       
    print("file opened")
    fp.close()

Output:
Unable to open the file

try:      
    a=10/2;  
    fp=open("file.txt","r")    
except ArithmeticError:      
    print("Arithmetic Exception")      
except IOError:      
    print("Unable to open the file")      

else:      
    print("Successfully Done")       
    print("file opened")
    fp.close()

Output:
Successfully Done
file opened

try:      
    a=10/0;  
    fp=open("file1.txt","r")    
except(ArithmeticError,IOError):      
    print("Arithmetic Exception/Unable to open the file")      
else:      
    print("Successfully Done")       
    print("file opened")
    fp.close()

Output:
Arithmetic Exception/Unable to open the file

Visitor Counter

0051130