下面是我使用raise的异常类
class SCE(Exception):
"""
An error while performing SCE functions.
"""
def __init__(self, value=None):
"""
Message: A string message or an iterable of strings.
"""
if value is None:
self._values = []
elif isinstance(value, str):
self._values = [value]
else:
self._values = list(value)
def __raise__(self):
print('raising')
if not len(self._values):
return
def __str__(self):
return self.__repr__()
def __iter__(self):
return iter(self._values)
def __repr__(self):
return repr(self._values)目前,如果我在没有值的情况下引发此异常,则会得到跟踪,然后是:
__main__.SCE: []而不是我所期望的那样:
raising
>>>如何过载raise
发布于 2010-02-01 23:49:37
正如另一个答案所述,没有__raise__的特殊方法。2004年,comp.lang.python上有一条帖子,有人建议添加这样的方法,但我不认为有任何后续行动。我能想到的挂钩异常引发的唯一方法是修补解释器,或者通过某种源或字节码重写将函数调用插入到raise操作的旁边。
发布于 2010-02-01 23:31:00
没有这样的特殊方法__raise__ (至少我从未听说过或在Python文档中可以找到)。
你为什么要这么做?我想不出为什么要在引发异常时执行自定义代码(而不是在构造异常时(可以用__init__方法执行异常),或者当异常被捕获时(可以用except块执行)。对于这种行为,您的用例是什么?为什么您希望Python支持它?
发布于 2019-06-28 19:01:40
正如其他人所指出的,没有这样的私有方法__raise__。没有什么能阻止定义一个。例如:
#!/usr/bin/env python3
class MyClass(object):
def __init__(self, raise_exceptions=False):
self.raise_exceptions = raise_exceptions
def __raise__(self, err=None):
print(err, flush=True)
if self.raise_exceptions:
raise err
def run(self):
try:
assert False, 'assertion False'
except Exception as err:
self.__raise__(err)
if __name__ == '__main__':
MyClass(raise_exceptions=False).run()
MyClass(raise_exceptions=True).run()这是输出:
$ python3 my_class.py
assertion False
assertion False
Traceback (most recent call last):
File "my_class.py", line 22, in <module>
MyClass(raise_exceptions=True).run()
File "my_class.py", line 17, in run
self.__raise__(err)
File "my_class.py", line 11, in __raise__
raise err
File "my_class.py", line 15, in run
assert False, 'assertion False'
AssertionError: assertion False
Process finished with exit code 1https://stackoverflow.com/questions/2180810
复制相似问题