通过调用它来区分相同的异常

时间:2011-01-23 04:02:05

标签: python python-3.x

我有一个不可避免的情况,看起来像这样(简化):

FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
  FUNCTION_TO_CALL(args, kargs)

def y(foo, bar=None):
  if foo == bar: # actually not this stupid
    raise TypeError()
  else:
    pass

def z(foo, bar, baz=None):
  pass

我知道,非常丑陋。 :(

但是,无论如何,我需要能够区分y中引发的TypeError,因为*args中没有任何内容或内容过多(因此没有足够的论点或太多)/坏kwargs或因为foo == bar

在实际设置中,可以调用的函数多于两个,并非所有函数都可以打开代码。

非常感谢!

3 个答案:

答案 0 :(得分:3)

您总是可以将自己的异常子类化为TypeError,并单独使用它们。

class TooManyArgumentsError(TypeError):
    pass
class EqualityError(TypeError):
    pass

答案 1 :(得分:2)

Matt Billenstein对Keith Morrow的回答是正确的做法。但另外,如果由于某些奇怪的原因你甚至不能这样做,你也可以查看inspect模块。

try: ugly()
except TypeError as e:
    stack = inspect.stack()
    [...look at the stack...]

Info about the inspect module.

详细说明“包装”问题:假设您可以控制哪些功能可以分配给FUNCTION_TO_CALL,请创建y_better

def y_better(foo, bar=None):
    try: y(foo, bar)
    except TypeError:
        if foo == bar: # detect foobar condition
            raise FoobarError()
        else:          # not foobar, so re-raise the exception
            raise

这意味着foo == bar正在测试两次,但考虑到你的限制,我没有看到更好的方法。

答案 2 :(得分:1)

定义自定义例外:

class yTypeError(TypeError):        通

然后在y()中并且仅在y()

中提高它
相关问题