简体   繁体   English

捕获异常后如何继续循环

[英]How to continue loop after catching exception

The below code produces exception while handling non int values but it doesn't continue the loop but rather comes out from the loop raising error. 下面的代码在处理非int值时会产生异常,但它不会继续循环,而是从循环引发错误中出来。 My intention is to provide the value of 0 for exception cases. 我的意图是为异常情况提供0值。

Sample Input: 输入样例:

Common Ruby Errors 45min
Rails for Python Developers lightning

Code: 码:

class TimeNotProvidedError(Exception):
    pass

def extract_input():
    lines = []
    __tracks = {}

    try:
        lines = [line.strip() for line in open('test.txt')]
    except FileNotFoundError as e:
        print("File Not Found", e)

    for line in lines:
        title, minutes = line.rsplit(maxsplit=1)
        minutes = int(minutes[:-3])
        try:
            __tracks[title] = minutes
        except TimeNotProvidedError:
            __tracks[title] = 0
    return __tracks

print(extract_input())

Traceback: 追溯:

ValueError: invalid literal for int() with base 10: 'lightn'

You're getting the error when converting to int with this line: minutes = int(minutes[:-3]) . 使用此行转换为int时,您会得到错误: minutes = int(minutes[:-3]) That line isn't in the try block, so the exception isn't caught. 该行不在try块中,因此未捕获到异常。 Move that line inside the try block, and you'll get the behavior you wanted. try块内移动该行,您将获得想要的行为。

Furthermore, the exception you're catching is TimeNotProvidedError , which isn't what int throws when a conversion fails. 此外,您捕获的异常是TimeNotProvidedError ,它不是转换失败时int抛出的异常。 Instead, it throws ValueError , so that's the exception type you need to catch. 相反,它将引发ValueError ,因此这是您需要捕获的异常类型。


The mere act of assigning to __tracks[title] is unlikely to cause an exception, and if it does , re-trying with another assignment probably won't work anyway. 分配给的单纯行为__tracks[title]不太可能导致异常,如果确实如此 ,再试图用另一种分配可能无论如何都不会工作。 What you probably want in your loop is this: 您可能想要的循环是这样的:

title, minutes = line.rsplit(maxsplit=1)
try:
    minutes = int(minutes[:-3])
except ValueError:
    minutes = 0
__tracks[title] = minutes

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

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