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