用户自定义异常:
class CustomException(Exception): def __init__(self, value): self.value = value 调用:raise CustomException("ERR-CONN_POOL: create_connect {}".format(str(e))) 外部使用try... except 接异常并打印,打印结果为空 修改异常类,添加 __str__:class CustomException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) 同样方式调用,异常可被打印。细究原因,官方文档对 __str__ 描述如下: Called by the str() built-in function and by the print statement。 ( __str__ 由str() 内置函数和 print 语句调用) 在执行 print 的时候会 调用 __str__ 对 __repr__ 的解释如下: Return a string containing a printable representation of an object. 返回一个对象的官方字符串表现形式 type(e) <class 'src.lib.custom_exception.CustomException'> 如若缺失解析对象为字符串这段代码,print是无法直接将类型为对象的变量打印出来的