gdo*_*371 8 python error-handling exception
我有一些代码可以遍历一系列 URL。如果由于其中一个 URL 不包含有效的 JSON 正文而导致我的代码出现错误,我希望将生成的错误打印到屏幕上,但随后代码会移至下一次迭代。我的代码的一个简单版本是:
for a in myurls:
try:
#mycode
except Exception as exc:
print traceback.format_exc()
print exc
pass
Run Code Online (Sandbox Code Playgroud)
但是,这会将错误打印到屏幕并结束代码的执行。有没有办法通过移动到“for”循环的下一次迭代来使错误继续执行?
Ani*_*rma 11
只需将 try-except 放在您希望发生异常的代码上。该代码基本上位于循环内。
for a in myurls:
try:
#mycode
except Exception as exc:
print traceback.format_exc()
print exc
Run Code Online (Sandbox Code Playgroud)