[英]How to use str to convert an exception object to string using str in Python?
I have seen code which 'converts' exception objects to the error string using str() like this: 我已经看到了使用str()将异常对象“转换”为错误字符串的代码,如下所示:
try:
...
except Exception, err:
print str(err)
Does err contain some public 'interface' through which its error string is fetched? err是否包含一些公共“接口”,通过该接口可以获取其错误字符串? I want to have the same functionality for my custom exception class.
我想为我的自定义异常类提供相同的功能。 One way i can think of doing is just define a global str() method for all my exception objects and then inside just return the error string using getter.
我能想到的一种方法是为所有异常对象定义一个全局str()方法,然后在内部使用getter返回错误字符串。 Is that how I should do it?
那是我应该怎么做?
只需为您的异常类定义__str__
方法即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.