Python Exception Handling

Example
#!/usr/bin/Python
a=int(raw_input("Enter First value"))
b=int(raw_input("Enter Second value"))
try:        
c=a/b;    
print'result=%d'%c
except:    print'Don\'t input zero as denominater'
print'Done 100%'
Exception handled  is output More keyword Exception.py
try:     
a=20/10
except:    
print' exception handler's
else:    
Print ‘ no exception ‘
finally:    
Print: 'cleanup code’
Clean up code Example
#!/usr/bin/python
# cleanup.py
f = None
try:   
f = file('indaclub', 'r')   
contents = f.readlines()   
for i in contents:      
print i,
except IOError:   
print 'Error opening file'
finally:   
if f:
     f.close()


Multiple except block
try:   
a=0/0
except ZeroDivsionError :      
print ‘ divide by zero error’
except:        print ‘ unknown error ‘


Another example
try:   
a=0/0
except Exception as im:    # I'm is object
print im

Reactions:

0 comments:

Post a Comment