简体   繁体   中英

How to use exception handling in a loop (for n iterations) in python so that results are stored in a file but loop doesn't terminate?

I want to raise exceptions in the form of logs in file and loop should not terminate if exception occurs in a particular iteration.

Input:

str = 'my name and age are not known'
for i in range(0,n):
    try:
        list =['name','age']
        for word in list:
           if word in str:
               print('output verified')
           else:
               raise Exception('unmatched values')
               print('unmatched values for iteration n')

     except Exception as ex:
        TestCase.status = FAIL
        raise ex

Output:

  unmatched values

I want output to be stored in a file and loop should continue for next iteration

Have a look into the below code logging in the file can be done as per requirement :

for i in range(0,n):
    try:
        list =['name','age']
        for word in list:
            if word in str:
                print('output verified')
            else:
                # instead of a generic exception a specific exception can be raised
                raise Exception('unmatched values')
                print('unmatched values for iteration n')
    except Exception:
        TestCase.status = FAIL
        print "Log you result in a file "
        # raise ex  - need not be here

Happy Coding :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM