将错误打印到屏幕但继续执行代码

时间:2015-06-14 20:26:09

标签: python exception error-handling

我有一些代码可以遍历一系列网址。如果我的代码中有错误,因为其中一个URL不包含有效的JSON正文,我希望生成的错误打印到屏幕,但随后代码移动到下一次迭代。我的代码的简单版本是:

for a in myurls:

    try:

        #mycode

    except Exception as exc:

        print traceback.format_exc()
        print exc
        pass

然而,这会将错误打印到屏幕并结束代码的执行。有没有办法通过转移到'for'循环的下一次迭代来让错误继续执行?

1 个答案:

答案 0 :(得分:3)

只需将try-except放在您希望发生异常的代码上。该代码基本上位于循环内。

for a in myurls:
    try:
        #mycode

    except Exception as exc:

        print traceback.format_exc()
        print exc
相关问题