try except loop python code example

Example 1: how to use try except in while loop in python

while True:  try:    num = int(input("Enter an int: "))  except Exception as e:    print(e)  else:    print("Thank you for the integer!")    break# Enter an int: a# invalid literal for int() with base 10: 'a'# Enter an int: 3# Thank you for the integer

Example 2: try for loop python

try:   
    with open('sample.txt','r') as file:
        for line in file:
            (some action here)
except IOError:
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)