将参数传递给自定义异常

Passing arguments into a custom exception

我最近学会了如何在 Python 中创建自定义异常并将它们实现到 class 中。为了更加清晰,我试图在我的异常中添加一个额外的参数,但似乎无法正确完成格式设置。

这是我正在尝试的:

class NonIntError(Exception):
    pass

class intlist(List):

    def __init__(self, lst = []):

        for item in lst:
            #throws error if list contains something other that int
            if type(item) != int:
                raise NonIntError(item, 'not an int') 

            else:
                self.append(item)

预期结果

il = intlist([1,2,3,'apple'])

>>> NonIntError: apple not an int

结果有误

il = intlist([1,2,3,'apple'])

>>> NonIntError: ('apple', 'not an int')

重申一下我的问题,我想知道如何让我的异常看起来像预期的结果。

您正在使用 两个 个参数 item 和字符串 'not an int' 初始化您的自定义异常。当您使用多个参数初始化 Exception 时,*args 将显示为元组:

>>> raise NonIntError('hi', 1, [1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.NonIntError: ('hi', 1, [1, 2, 3])

要获得您想要的结果,请只传递一个字符串,即:

>>> item = 'apple'
>>> raise NonIntError(item + ' not an int')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.NonIntError: apple not an int

根据你的class和timgeb的回答,我有一个更好的答案:

当你检查列表的元素是否为int时,我建议你:

class intlist(object):

    def __init__(self, lst = []):
        not_int_list = filter(lambda x: not isinstance(x, int), lst)
        if not_int_list:
            if len(not_int_list) > 1:
                items = ', '.join(not_int_list)
                raise NonIntError(items + ' are not int type')
            item = not_int_list.pop()
            raise NonIntError(item + ' is not int type')

il = intlist([1,2,3,'apple'])时,会return:

>>> NonIntError: apple is not int type

il = intlist([1,2,3,'apple','banana'])时,会return:

>>> NonIntError: apple, banana are not int type

增强了可读性,当列表包含单个或多个非整数元素时会return适当的错误信息。


解释:

not_int_list = filter(lambda x: not isinstance(x, int), lst)

使用 filterisinstance 将帮助您编码可读的 class 对象和检查机制。

if len(not_int_list) > 1:
    items = ', '.join(not_int_list)
    raise NonIntError(items + ' are not int type')
item = not_int_list.pop()
raise NonIntError(item + ' is not int type')

当列表有一个或多个无效元素时,它会return适当的错误信息。

NonIntError(items + ' are not int type')

来自timgeb的回答。不用多解释了。