Nov-01-2020, 10:14 PM
Using a simplified version of your example:
Wrapping an exception handler around each print statement fixes the problem, because each print statement gets evaluated. However I think this is a case where look before you leap is better than relying on an exception handler.
cnttt = 1 cntt1 = 0 lstt0 = ['lst0'] lstt1 = [] try : print ("-- Count of 'Error - 0' Errors -- "+ str(cnttt)+" --->>> "+lstt0[-1]+"\n") print ("-- Count of 'Error - 1' Errors -- "+ str(cntt1)+" --->>> "+lstt1[-1]+"\n") except Exception as ex: print(ex)
Output:-- Count of 'Error - 0' Errors -- 1 --->>> lst0
list index out of range
This looks like the exception works. It prints the message followed by the exception. But what happens if we change lst0 = [] and lst1 = ['lst1']. When I do this the output is:Output:list index out of range
Why is there only 1 message? The answer is easy if we trace the code. We try to print the first message and it fails because the list is empty and there is nothing to get at lst0[-1]. This throws an exception and we move down to the handler that prints the exception. Execution continues on from that point. It does not jump back to the next line after the exception. Just imagine how horrible that would be if you wrapped an exception handler around a loop. You might never escape.Wrapping an exception handler around each print statement fixes the problem, because each print statement gets evaluated. However I think this is a case where look before you leap is better than relying on an exception handler.
if (len(lstt0(> 0): print ("-- Count of 'Error - 0' Errors -- "+ str(len(lstt0))+" --->>> "+lstt0[-1]+"\n") if (len(lstt0) > 0): print ("-- Count of 'Error - 1' Errors -- "+ str(len(lstt1))+" --->>> "+lstt1[-1]+"\n")