简体   繁体   English

我应该在try-except块中添加else语句来处理return语句吗?

[英]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. 我通过枚举列表来比较当前项目中的数字与下一个项目,并检查下一个项目中的数字仅比1大,从而使用了for循环。在我看来,我应该使用try-except块这样,当循环的最后一次迭代运行并尝试与不存在的下一个项目进行比较时,我不会收到IndexError。

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:
        if 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. 这段代码有效,但是我读到您应该避免在try块本身中放置太多代码,以避免添加可能引发来自其他位置(而不是打算测试的代码部分)的异常的代码。 In this case, should I add an else statement in the try-except block to place the return statement? 在这种情况下,是否应在try-except块中添加else语句以放置return语句? How do I manage the if statement in that case? 在这种情况下,我该如何管理if语句?

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. 在我看来,我应该使用try-except块,以便在运行循环的最后一次迭代并尝试与不存在的下一个项目进行比较时,不会收到IndexError。

I think a better solution is to write code that doesn't raise exceptions under normal conditions. 我认为更好的解决方案是编写在正常情况下不引发异常的代码。

Instead of comparing the current item to the next item, which as you noted will cause an exception on the last item, you can iterate starting on the second item and compare to the previous item: 相反,目前的项目比较下一个项目,正如你提到会造成的最后一项例外,你可以遍历开始的第二个项目,并比较以前的项目:

for i in range(1, len(file_list)):
    # compare file_list[i] to file_list[i-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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