我正在我的 python 代码中自定义异常。我已将异常类继承到其他类,现在将一些自定义错误定义为从我的自定义异常类派生的类,如下所示:
class DataCollectorError(Exception): pass
class ParamNullError(DataCollectorError) : pass
class ParamInvalidTypeError(DataCollectorError) : pass
我在我的 python 函数中提出了这些异常,例如:
def READ_METER_DATA (regIndex, numRegisters, slaveUnit):
try:
if not regIndex:
raise ParamNullError, "register index is null"
if not numRegisters:
raise ParamNullError, "number of registers should not be null"
if not slaveUnit:
raise ParamNullError, "Meter Id should not be null"
并记录错误,例如:
except DataCollectorError as d:
lgr.error('DataCollector Error(READ_METER_DATA): '+d.args[0])
print 'DataCollector Error:(READ_METER_DATA)', d.args[0]
except:
lgr.error('Unexpected Error: ', sys.exc_info())
print 'Unexpected Error: ', sys.exc_info()
pass
但这违背了单元测试脚本的目的,因为它不会在我的单元测试脚本知道之前被我的 catch 块捕获是否引发异常。所以我想在基类本身中记录这些错误-
Class ParamNullError(DataCollectorError):
<----here----------->
pass
谁能告诉我如何在引发异常时获取传递的字符串?