2

I have a python selenium script that runs through a loop like this...

for i, refcode in enumerate(refcode_list):

    try:
        source_checkrefcode()
    except TimeoutException:
        pass
        csvWriter.writerow([refcode, 'error', timestamp])

If there is a problem during the source_checkrefcode then the script crashes with an error.

How can I add error handling to this loop so that it just moves to the next item instead of crashing?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

2 Answers2

10

You can add a check over exception message, below is the sample code for your understanding.

for i, refcode in enumerate(refcode_list):
    try:
        source_checkrefcode()
    except Exception as e:
        if 'particular message' in str(e):
            # Do the following
            # if you don't want to stop for loop then just continue
            continue
Hassan Mehmood
  • 1,414
  • 1
  • 14
  • 22
  • My original code looks out for TimeoutException but your example uses Exception. Will this new code still catch the TimeoutException as well? – fightstarr20 May 17 '16 at 10:48
  • Yes, Actually Exception will catch all types of exceptions. Then you can add a check on its string message. For example. If 'TimeountException' in str(e): do this elif 'Another Exception' in str(e): do this and so on – Hassan Mehmood May 17 '16 at 10:49
0

I agree with Hassan's Answer. But if you use continue then you won't process any other block of code.

for i, refcode in enumerate(refcode_list):
    try:
        source_checkrefcode()
    except Exception as e:
        if 'particular message' in str(e):
            # Do the following
            # if you don't want to stop for loop then just continue
            continue
    # another code of block will skip. Use pass or continue as per your requirement.

You must understand the difference between pass and continue Link

Community
  • 1
  • 1
Vardhman Patil
  • 517
  • 6
  • 22