简体   繁体   English

在for循环中使用try / catch块的正确方法是什么?

[英]What is correct way to use try/catch block in case of for loop?

I am confused as to how should I use try-catch block with for loops. 我对应该如何将try-catch块与for循环一起使用感到困惑。 Is there any standard we should follow for this. 有什么我们应该遵循的标准。 These are some sample codes. 这些是一些示例代码。 Which one should be the preferred approach? 哪一种是首选方法?

def func1():
    try:
        for i in range():
            do_something()
    except:
        print(error)


def func1():
    for i in range():
        try:
            do_something()
        except:
            print(error)

Or in case of using multiple for loops: 或在使用多个for循环的情况下:

def func3():
    try:
        for i in range():
            for j in range():
                do_something()
    except:
        print(error)

def func4():
    for i in range():
        for j in range():
            try:
                do_something()
            except:
                print(error)

Depends on the condition, if you have a multiple for loop, and the function in the inner loop throws an error, do you want to continue running the for loop for other inputs, or you want to stop the for loop execution completely. 根据条件,如果您有多个for循环,并且内部循环中的函数引发错误,是否要继续为其他输入运行for循环,还是要完全停止for循环执行。

If you want to continue running the loop, then having the try catch inside the for loop makes sense like below, so that you still continue looping 如果您想继续运行循环,那么将try catch放入for循环中是很有意义的,如下所示,因此您仍然可以继续循环

As always, you can have a finally condition in either of your try-catch logic which might do something for you! 与往常一样,您可以在任何一种尝试捕获逻辑中都具有finally条件,这可能会对您有所帮助!


def func4():
    for i in range():
        for j in range():
            try:
                do_something()
            except:
                print(error)

But if you want to stop looping in case an exception happens, keeping the try-catch outside the loop makes sense 但是,如果您想停止循环以防发生异常,则将try-catch保留在循环之外很有意义

def func3():
    try:
        for i in range():
            for j in range():
                do_something()
    except:
        print(error)

The first approach does have a caveat where if you have a loop running 100 times, and the exception is thrown 10 times, maybe you need to handle it every time in a different way or suppress it, and you are not sure if more exceptions will be thrown down the line once more loops run. 第一种方法确实有一个警告,如果循环运行了100次,并且抛出了10次异常,也许您每次都需要以不同的方式处理它或抑制它,并且您不确定是否会有更多的异常会发生一旦有更多的循环运行,就被抛弃。 An example where catching exception inside a for loop is beneficial might will be if you are processing a list of lists, and some sublists have bad elements in it, and you want to ignore them and keep the res.t 如果正在处理列表列表,并且某些子列表中包含不良元素,而您想忽略它们并保留res.t,那么在for循环中捕获异常是有益的一个示例可能是。

Whereas in the second approach, you just stop on the first exception and give up on looping, which might be bad if your data size you are looping on is pretty big, and you need to restart the loop every time, but might be beneficial if you want to correct your dataset at the first error you see and run it again! 而在第二种方法中,您只是在第一个异常上停止并放弃循环,如果要循环的数据量很大,并且每次都需要重新启动循环,则这可能会很糟糕,但是如果您要循环,则可能会有所帮助您想在看到第一个错误时更正数据集,然后再次运行它!

It depends on your situation. 这取决于您的情况。

If you need a complete success operation to continue, you may want to put the try/catch outside the loop. 如果需要完成成功操作才能继续,则可能需要将try / catch置于循环之外

If your results in loop won't effect each other, you can put the try/catch inside the loop. 如果循环中的结果不会互相影响,则可以将try / catch 放入循环中。

For example, downloading contents from website (the loop won't break when error): 例如,从网站下载内容(错误时循环不会中断):

contents = []
for i in range(100):
  try:
    contents.append(requests.get("http://example.com/%d.html" % i))
  except:
    print("page %d is not available.", i)

Updating game or applications (break the loop when error): 更新游戏或应用程序(出错时中断循环):

updateList = ["File1.jpg", "File2.jpg"]
try:
  for file in updateList:
    res = requests.get("http://example.com/%s" % file)
except:
  print("Update has failed, application cannot continue.")

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

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