是否有应明确跟踪或忽略的事件?

时间:2019-05-14 22:27:03

标签: python python-3.x error-handling

在研究解决How to automatically re-raise exception after handlers的过程中,开发了一个异常类,该异常类具有在处理完异常后能够自动抛出自身的功能(受C#中的ThreadAbortException启发)。经过大量的反复试验,该类已被证明可在最简单的情况下工作。我担心的是,如果异常处理程序调用函数或异常处理程序具有自己的try并且其中包含处理程序块,则可能会产生不必要的开销。

到目前为止,该类及其测试是这样:

#! /usr/bin/env python3
import dis
import inspect
import sys


def main():
    try:
        raise SpecialError
    except SpecialError as error:
        print(f'{error!r} was caught!')
        # error.reset()
    print('You should not see this!')


class SpecialError(BaseException):
    DEBUG = False
    THROW = {dis.opmap['END_FINALLY'], dis.opmap['POP_EXCEPT']}

    def __init__(self, *args):
        super().__init__(*args)
        self.__stack = []
        frame = inspect.currentframe()
        while frame:
            self.__stack.append((frame, frame.f_trace))
            frame.f_trace = self.__trace
            frame = frame.f_back
        self.__saved = sys.gettrace()
        sys.settrace(self.__trace)

    def __trace(self, frame, event, arg):
        frame.f_trace_lines = False
        frame.f_trace_opcodes = True
        if event == 'opcode':
            op = frame.f_code.co_code[frame.f_lasti]
            if self.DEBUG:
                print(dis.opname[op])
            if op in self.THROW:
                raise self
        return self.__trace

    def reset(self):
        sys.settrace(self.__saved)
        for frame, trace in self.__stack:
            frame.f_trace = trace


if __name__ == '__main__':
    main()

是否有任何应禁用跟踪的事件,并且应将任何操作码记录到堆栈中并弹出以检测异常何时应真正再次引发自身(在处理程序块结束后被捕获) ?

0 个答案:

没有答案