Saturday, 23 September 2017

How to handle exceptions in Python ?


SYNTAX
try:
   ...
except:
   ...
finally
  ...


EXAMPLE
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print(entry)
        r = 1/int(entry)
        break
    except:
        print('Oops', sys.exc_info()[0], "occured")
        print('next entry')
    finally:
        print("finally !!!")


print('The reciprocal of', entry, "is", r)

 

No comments:

Post a Comment

Note: only a member of this blog may post a comment.