如何在引发异常时更改异常?

时间:2014-05-04 16:10:12

标签: python python-3.x

我正在为我的操作系统类创建一个模拟操作系统。涵盖的一个主题是中断和错误。我将做一个简单的案例:

def read_instructions():
  try:
    with open('assembly.txt', 'r') as assembly:
      for line in assembly:
        status = execute_instruction(line) # this will also raise an error if instruction is invalid
  except IOError as e:
    raise IOError(1)

我想要更像这样的东西,而不是像[err 2] File Not Found]这样的东西沿着那些默认的python线,

def Exceptions(e):
  """ this is meant to be a 'fake' event-vector table """
  self.controller[status] = e # all exceptions will do this
  def io_exception():
    print('failed while trying to find your file')
    # some traceback and logging shenanigans here
    shutdown_system()

  def invalid_assembly():
    print('your assembly line did not follow instruction set')
    # more traceback
    shutdown_system()

  def unimplemented():
    print("you made an error I didn't catch. You've won this round.")

  return {
    1: io_exception,
    2: invalid_assembly
  }.get(e, unimplemented)()

是否可以覆盖引发异常的位置,而是将它们放在这里?

1 个答案:

答案 0 :(得分:3)

在他们点击except关键字之前,异常会冒泡。如果它们在当前执行上下文之外(也就是它们 untrapped ),它们会导致Python打印堆栈跟踪和错误中包含的消息(通常会终止发生的线程)。

您当然可以使用自己的类扩展Exception或任何其他标准错误类型,并在其上使用raise,但您无法更改异常系统的工作方式,它是语言的一部分说明书

所以你应该做的是在'OS',陷阱所有例外情况中:

try:
    run_task() # Runs an OS task
except Exception as e:
    # Do OS exception handling here. This will trap any exception thrown by a task.

然后用这个例外做任何你想做的事。

您甚至可以定义自己的基本例外:

class OSBaseException(Exception):
    def __init__(self, *args, **kwargs):
        super(Exception, self).__init__(*args, **kwargs)
        # any other init here
    # An OS specific method hooks here

您希望扩展所有用户的异常,从而为操作系统的陷阱系统提供一些额外的挂钩。

Curious Course on Coroutines and Concurrency实际上提供了一个很好的例子来说明你正在做的事情。

请注意,您将要压缩所有堆栈跟踪,这对于使用您的操作系统的“开发人员”来说可能很烦人。

相关问题