lundi 26 août 2019

Should I add an else statement to try-except block to handle the return statement?

I am trying to compare items in a list and find any locations where an item may be missing.

I am using a for loop by enumerating the list to compare the number within the current item with the next item and check that the number within the next item is only larger by 1. It seems to me that I should use a try-except block so that I don't receive an IndexError when the last iteration of the loop is ran and tries to compare to the next item that doesn't exist.

file_list = []
for i in range(100):
    file_list.append('img' + str(i).zfill(3) + '.tif')

del file_list[50]

for i, file in enumerate(file_list):
    try:
        int(file[3:6]) + 1 != int(file_list[i + 1][3:6]):
            return 'File missing after {}'.format(file_list[i])
    except IndexError:
        print('IndexError at i = {}'.format(i))

This code works, however I have read that you should try to avoid placing much code in the try block itself to avoid adding code that could raise exceptions from other locations than the portion of the code that is intended to be tested. In this case, should I add an else statement in the try-except block to place the return statement? How do I manage the if statement in that case?

Aucun commentaire:

Enregistrer un commentaire