【问题标题】:python-help learning how to deal with errors using try-except [duplicate]python-help学习如何使用try-except处理错误[重复]
【发布时间】:2016-05-26 07:20:23
【问题描述】:

我是网站和 python 的新手。我正在学习如何使用 try-except 处理错误。我要求输入以打开文件并搜索一行。这是我现在拥有的程序。它主要工作......

try:  
    file_str = input("Open what file:")
    input_file = open(file_str) # potential user error
    find_line_str = input("Which line (integer):")
    find_line_int = int(find_line_str) # potential user error
    line_count_int = 1
    for line_str in input_file:
        if line_count_int == find_line_int:
            print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
            break
        line_count_int += 1

    else: # get here if line sought doesn't exist
        print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
except IOError:
    while True:
        file_str = input("That file was not found. Please try again:")
except ValueError:
    find_line_str = input("Invalid line value. Please try again:")

print("End of the program")

最初,如果出现错误,它会说“无效输入,程序结束”现在我试图让程序继续要求输入,直到用户正确为止。

通过我在 except IOError 中放入的 while 循环,即使我输入了有效的文件名,它也会永远循环。如果我只是要求输入,它会在输入后结束程序。

如何让它在收到有效输入后返回并运行 for 循环?几个小时以来,我一直在努力解决这个问题,我非常感谢您的帮助。

【问题讨论】:

  • while 将在下一行循环。

标签: python python-3.x


【解决方案1】:

简而言之

while True:
    try:  
        #code
        break #success case
    except IOError:
        #error display
        #no break, the loop goes on

【讨论】:

  • 最佳答案。这个问题需要所有的细节,因为提问者不知道哪里出了问题。省略不相关的东西,答案就更清楚了。也是“不断尝试,捕捉异常,直到我们成功”的模板。
【解决方案2】:

您自己的脚本的更新版本。添加了一个while循环。如果出现 ValueError 或 IOError,以下脚本将从顶部重新开始。

while True:
    try:  
        file_str = input("Open what file:")
        input_file = open(file_str) # potential user error
        find_line_str = input("Which line (integer):")
        find_line_int = int(find_line_str) # potential user error
        line_count_int = 1
        for line_str in input_file:
            if line_count_int == find_line_int:
                print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
                break
            line_count_int += 1

        else: # get here if line sought doesn't exist
            print("Line {} of file {} not found".format(find_line_int,file_str))
        input_file.close()
        break
    except IOError:
        print "That file was not found. Please try again:"
    except ValueError:
        print "Invalid line value. Please try again:"

print("End of the program")

【讨论】:

  • 哇,这么近,但这么远……谢谢哈桑!!!
【解决方案3】:

通过我在 except IOError 中放入的 while 循环,即使我输入了有效的文件名,它也会永远循环。如果我只是要求输入,它会在输入后结束程序。

当然会:

except IOError:
    while True:
        file_str = input("That file was not found. Please try again:")

一旦发生第一个IOError,就无法打破while 循环。

根据经验,您应该在每个try 块中保留最少的行数。这样您就可以更好地控制引发异常的行。

在这种情况下,您应该try 在while 循环中打开文件,如果成功则中断,如果发生异常则继续循环:

while True:
    file_str = input("Open what file:")
    try:
        input_file = open(file_str) # potential user error
        break
    except IOError:
        print('File not found. Try again')
# rest of code

【讨论】:

    【解决方案4】:

    你的 try/except(s) 应该放在一个 while 条件循环中。

    要退出循环,您可以:

    • 在进入循环之前将条件标志设置为 True 并在进入正常后立即设置为 False - 您将继续循环处理任何错误
    • 或在 'while True:' 循环中的正确条目的末尾添加一个 'break'

    在这两种情况下,您都应该接受用户的某些请求(类似于“取消”用例)退出循环。

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2022-10-08
      • 1970-01-01
      相关资源
      最近更新 更多