[英]How do you print an error with Try and Except
I feel stupid asking this since the answer is probably simple but I couldn't really find the answer by googling it... I have a lot of code which I don't want help with, I want to debug on my own, and I use try/except for it, but except doesn't print the error messsage and I couldn't find a way to print that.我觉得问这个问题很愚蠢,因为答案可能很简单,但我无法通过谷歌搜索真正找到答案......我有很多代码不想得到帮助,我想自己调试,并且我使用 try/except ,但 except 不打印错误消息,我找不到打印它的方法。 Basically, how do I check what my error is?基本上,我如何检查我的错误是什么?
Firstly to check what is your error, you can watch into your terminal there will be error's name:首先要检查你的错误是什么,你可以在你的终端中看到错误的名称:
print(5+"5")
>>>
Traceback (most recent call last):
File "c:\Users\USER\Desktop\how_to_use_try_except.py",
line 1, in <module>
print(5+"5")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
and to catch it, you need to copy error's name, and except it要捕获它,您需要复制错误的名称,并将其排除在外
try:
print(5+"5")
except TypeError:
print("You can't add string value to int!")
also you can write你也可以写
try:
print(5+"5")
except TypeError as e:
print(e)
>>>
unsupported operand type(s) for +: 'int' and 'str'
You can use traceback
, more specifically traceback.print_exc()
.您可以使用traceback
,更具体地说是traceback.print_exc()
。 This prints the full error traceback, rather than just the one line produced from using as
in your except
block.这将打印完整的错误回溯,而不仅仅是在except
块中使用as
产生的一行。
I've put an example below using a ValueError
.我在下面使用ValueError
举了一个例子。
import traceback
try:
int("s")
except ValueError:
traceback.print_exc()
This produces the same print result as if there was no try-except, the difference being that this solution allows the code to continue running.这会产生与没有 try-except 相同的打印结果,不同之处在于此解决方案允许代码继续运行。
You CAN use try except to catch ANY error without worrying for its types.你可以使用 try except 来捕获任何错误而不用担心它的类型。 Use this code使用此代码
try:
blah blah
except Exception as A: #(Where A is a temporary variable)
print(a)
Tadaaa, you just captured the error without blowing your whole code. Tadaaa,您只是捕获了错误而没有破坏整个代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.