python exception handling



-------------------------ZeroDivisionError--------------------------------
-
a=int(raw_input("Enter First value"))
b=int(raw_input("Enter Second value"))
try:
 res=a/b
except ZeroDivisionError:
 print 'Dont enter b as zero'
else:
 print ' Result= %d'%res

print "Done 100%"

-----------------------FileHandling----------------------------------
#!/usr/bin/python
a=input("Enetr a")
b=input("Enter b")
try:
        fh=open("a1.txt","r")
        #print a/b
except Exception:
        print "File cannot be open"

else:
        print fh.read()

print "bye!!!"

__________________finally___________

#!/usr/bin/python
a=input("Enetr a")
b=input("Enter b")
fh=None
try:
        fh=open("a1.txt","r")
        print "File openend successfully"
except IOError:
        print "File cannot be open"

else:
        print fh.read()
finally:
        if fh:
                fh.close()
                print "Fiie closed succefully"

print "bye!!!"




Reactions:

0 comments:

Post a Comment