class My_custom_exception(Exception):
def __init__(self, ErrNum, *arg, **kwargs):
self.ErrNum = int(ErrNum)
self.ErrMsg = "" # Set appropriate message depending an error number
if self.ErrNum & 0x00000000 !=0:
self.ErrMsg = "NO ERROR"
if self.ErrNum & 0x00000001 !=0:
self.ErrMsg = "Error 1 occured"
if self.ErrNum & 0x00000002 !=0:
self.ErrMsg = "Error 2 occured"
if self.ErrNum & 0x00000004 !=0:
self.ErrMsg = "Error 3 occured"
if self.ErrNum & 0x00000008 !=0:
self.ErrMsg = "Error 4 occured"
def __str__(self):
return "ERROR (0x%08X): %s" % (self.ErrNum, self.ErrMsg )
def __repr__(self):
return self.__str__()
def check_error(error_nr):
if error_nr > 0:
raise My_custom_exception(error_nr)
try:
check_error(3)
except My_custom_exception as e:
print e
输出:
My_custom_exception (0x00000003): Error 2 occurred.
我的目标是同时打印Error 1 occurred
和Error 2 occurred
。
如果我给check_error(5)
然后Error 4 occurred
,我还想避免这种情况,这是另一个问题。
答案 0 :(得分:2)
我会这样做:
class MyCustomException(Exception): # note naming convention
MESSAGES = {
0x00000000: 'NO ERROR',
0x00000001: 'Error 1 occurred',
0x00000002: 'Error 2 occurred',
0x00000004: 'Error 3 occurred',
...
}
def __init__(self, err_num, *args, **kwargs):
super(MyCustomException, self).__init__(*args, **kwargs) # handle inheritance
self.err_num = int(err_num)
self.err_msg = self._create_err_msg(self.err_num)
def __str__(self):
return "ERROR (0x%08X): %s" % (self.err_num, self.err_msg)
def __repr__(self):
# Note that __repr__ should be eval-able
return 'MyCustomException(%d)' % self.err_num
@classmethod
def _create_err_msg(cls, err_num):
messages = []
for num, msg in cls.MESSAGES.items():
if err_num & num:
messages.append(msg)
return ' and '.join(messages) if messages else cls.MESSAGES[0]
请注意,这通过将错误消息提取到字典类属性中来简化代码;使它成为一个单独的方法也使得更容易单独测试:
>>> MyCustomException._create_err_msg(5)
'Error 1 occurred and Error 3 occurred'
>>> MyCustomException._create_err_msg(2)
'Error 2 occurred'
>>> MyCustomException._create_err_msg(0)
'NO ERROR'
使用中:
>>> exc = MyCustomException(5)
>>> str(exc)
'ERROR (0x00000005): Error 1 occurred and Error 3 occurred'
答案 1 :(得分:1)
这可能有效:收集列表中的错误(格式化可能需要一些工作,但这应该是一个开始):
class My_custom_exception(Exception):
def __init__(self, ErrNum, *arg, **kwargs):
self.ErrNum = int(ErrNum)
self.ErrMsgs = []
if self.ErrNum & 0x00000000 !=0:
self.ErrMsgs = ["NO ERROR"]
if self.ErrNum & 0x00000001 !=0:
self.ErrMsgs.append("Error 1 occured (0x00000001)")
if self.ErrNum & 0x00000002 !=0:
self.ErrMsgs.append("Error 2 occured (0x00000002)")
if self.ErrNum & 0x00000004 !=0:
self.ErrMsgs.append("Error 3 occured (0x00000004)")
if self.ErrNum & 0x00000008 !=0:
self.ErrMsgs.append("Error 4 occured (0x00000008)")
def __str__(self):
return "ERRORS: %s" % ', '.join(self.ErrMsgs)
示例的输出:
ERRORS: Error 1 occured (0x00000001), Error 2 occured (0x00000002)