0

所以我有一个执行某些操作的 for 循环,我需要在上面创建一个 try-except 语句(用于打开文件,如果找不到文件则异常),但是下面的 for 循环出现语法错误它(尽管当我选择错误的文件时它确实给了我异常消息)。遇到异常后如何阻止程序运行循环?

我认为使用 break 可能与它有关,但不太确定如何。我正在考虑是否打印我的异常消息然后中断或类似的东西。这是有问题的代码:

def getIngredients(path, basename):
  ingredient = []
  filename = path + '\\' + basename
  try:
    file = open(filename, "r")
  except:
    printNow("File not found.")

  for item in file: 
    if item.find("name") > -1:
      startindex = item.find("name") + 5
      endindex = item.find("<//name>") - 7
      ingredients = item[startindex:endindex]
      ingredient.append(ingredients)

  del ingredient[0]
  del ingredient[4]


  for item in ingredient:
    printNow(item)

基本上,因为我选择了错误的文件来获取异常,所以下面使用该文件的 for 循环给了我一个错误。

4

4 回答 4

1

Well, you need to decide what you want to happen if the file is not found.

You could choose to simply return from the function:

def getIngredients(path, basename):
    ingredient = []
    filename = path + '\\' + basename
    try:
        file = open(filename, "r")
    except IOError:                 # Never use a bare "except"! Be specific!
        printNow("File not found.")
        return

    for item in file: 
        ...

    return ingredient

That way, the caller can check from the return value whether the function completed successfully (if that matters):

  • If an error occurred before the loop was run, None is returned.
  • If the loop doesn't find any matches, an empty list [] is returned.
  • Otherwise, the list of results is returned.
于 2012-05-12T07:57:48.400 回答
0

I'm guessing you want to exit the function if the file is wrong. Then this will do it:

except:
  printNow("File not found.")
  return
于 2012-05-12T07:56:38.527 回答
0

根据我对您的问题的理解,每次遇到异常时,您都会将flag变量设置为1(或true)。然后简单地将你的 - 包围起来loopif-statement然后不要执行,否则,执行它。ifflagloop

或者,如果您(出于某种原因)确实需要进入循环,那么您可以选择将if clause循环置于内部并使用break语句来跳出或退出循环。

有关python中的 break 语句的更多信息,以及如何在循环中使用它的示例。

于 2012-05-12T07:45:38.023 回答
0

在循环中 使用一段break时间,以摆脱它。except

>>> while True:  
...     try:  
...         x = int(raw_input("Please enter a number: "))  
...     except ValueError:  
...         print "Oops! That was no valid number. Try again..."  
...         break  
...
于 2012-05-12T07:49:59.220 回答