简体   繁体   中英

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. 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:

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.

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

As always, you can have a finally condition in either of your try-catch logic which might do something for you!


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

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. 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

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.

If your results in loop won't effect each other, you can put the try/catch inside the loop.

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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