在屏幕上打印错误,但继续执行代码 [英] Print error to screen but continue code execution

查看:62
本文介绍了在屏幕上打印错误,但继续执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以通过一系列URL进行迭代。如果由于其中一个URL不包含有效的JSON主体而导致我的代码中出现错误,我希望将生成的错误打印到屏幕上,然后将代码移至下一个迭代。我的代码的简单版本为:

I have some code that iterates through a series of URLs. If there is an error in my code because one of the URLs does not contain a valid JSON body, I want the error generated to be printed to screen, but then the code moves onto the next iteration. A simple version of my code is:

for a in myurls:

    try:

        #mycode

    except Exception as exc:

        print traceback.format_exc()
        print exc
        pass

但是这会在屏幕上显示错误并结束代码的执行。有没有办法通过移至我的 for循环的下一个迭代来使错误继续执行?

However this prints the error to screen and ends execution of the code. Is there a way I can get the error to continue execution by moving to the next iteration of my 'for' loop?

推荐答案

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

Just put try-except over the code for which you expect an exception to occur. That code basically lies inside the loop.

for a in myurls:
    try:
        #mycode

    except Exception as exc:

        print traceback.format_exc()
        print exc

这篇关于在屏幕上打印错误,但继续执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆