4

这是我使用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

4

3 回答 3

3

正如另一个答案所说,没有__raise__特殊的方法。2004 年 comp.lang.python 上有一个帖子有人建议添加这样的方法,但我认为没有任何后续行动。我能想到的挂钩异常引发的唯一方法是修补解释器,或者在引发操作旁边插入函数调用的某种源代码或字节码重写。

于 2010-02-01T23:49:37.630 回答
1

没有这样的特殊方法__raise__(至少没有我听说过或在Python 文档中可以找到的方法)。

你为什么要这样做?我想不出任何理由为什么要在引发异常时执行自定义代码(而不是在构造异常时,您可以使用该__init__方法执行此操作,或者在捕获异常时,您可以做一个except块)。您对此行为的用例是什么,为什么您希望 Python 支持它?

于 2010-02-01T23:31:00.007 回答
0

正如其他人所说,没有这样的私有方法__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 1
于 2019-06-28T19:01:40.907 回答