擅长:python、mysql、java
<p>您可以通过捕获异常来实现这一点:</p>
<pre><code>try:
exec(my_code_with_error)
except Exception as e:
print(e)
</code></pre>
<p>雷蒙德在我写我的答案时也给出了类似的答案。
Raymond的答案在Python2中也可以使用(请参见“问题”中的<a href="https://wiki.python.org/moin/HandlingExceptions" rel="nofollow noreferrer">https://wiki.python.org/moin/HandlingExceptions</a>,“一般错误处理”),并且还具有输出错误类的优势</p>