Python中.Net InvalidOperationException的模拟是什么?

时间:2010-03-31 16:37:54

标签: .net python exception invalidoperationexception

InvalidOperationException中.Net Python的模拟内容是什么?

4 个答案:

答案 0 :(得分:12)

没有直接的等价物。通常ValueErrorTypeError就足够了,如果两者都不合适,可能是RuntimeErrorNotImplementedError

答案 1 :(得分:5)

我可能介于两个选项之一:

  1. 自定义异常,最佳定义如下:

    class InvalidOperationException(Exception): pass

  2. 只需使用Exception

  3. 我不相信有直接的模拟; Python似乎有一个非常平坦的异常层次结构。

答案 2 :(得分:3)

我将部分同意Chris R - 定义你自己的:

     class InvalidOperationException(Exception): pass

通过这种方式定义自己的异常会带来很多好处,包括构建满足您需求的层次结构:

     class MyExceptionBase(Exception): pass
     class MyExceptionType1(MyExceptionBase): pass
     class MyExceptionType2(MyExceptionBase): pass
     # ...
     try:
        # something
     except MyExceptionBase, exObj:
        # handle several types of MyExceptionBase here...
但是,我不同意抛出赤裸裸的“例外”。

答案 3 :(得分:0)

我认为您应该这样做

return NotImplemented

而不是定义自己的异常。在这种情况下,请参见以下示例:

class InvalidOperationException(Exception):
    pass


class Vector2D(list):
    def __init__(self, a, b):
        super().__init__([a, b])

    def __add__(self, other):
        return Vector2D(self[0] + other[0],
                        self[1] + other[1])

    def __mul__(self, other):
        if hasattr(other, '__len__') and len(other) == 2:
            return self[0]*other[0] + self[1]*other[1]
        return Vector2D(self[0]*other, self[1]*other)

    def __rmul__(self, other):
        if hasattr(other, '__len__') and len(other) == 2:
            return Vector2D(other[0]*self, other[1]*self)
        return Vector2D(other*self[0], other*self[1])


class Matrix2D(list):
    def __init__(self, v1, v2):
        super().__init__([Vector2D(v1[0], v1[1]),
                          Vector2D(v2[0], v2[1])])

    def __add__(self, other):
        return Matrix2D(self[0] + other[0],
                        self[1] + other[1])

    def __mul__(self, other):
        # Change to:
        # return InvalidOperationException
        # or:
        # raise InvalidOperationException
        return NotImplemented


if __name__ == '__main__':

    m = Matrix2D((1, -1),
                 (0,  2))

    v = Vector2D(1, 2)

    assert v*v == 5  # [1 2] [1] = 5
    #                        [2]

    assert v*m == Vector2D(1, 3)  # [1 2] [1 -1] = [1 3]
    #                                     [0  2]

    try:
        result = m*m
        print('Operation should have raised a TypeError exception, '
              'but returned %s as a value instead' % str(result))
    except TypeError:
        pass

    assert m*v == Vector2D(-1, 4)  # [1 -1] [1] = [-1]
    #                                [0  2] [2]   [ 4]

它应该可以正常运行。执行m*v时,它尝试从__mul__调用Matrix2D,但失败。当且仅当它返回NotImplemented时,它才会尝试从右侧的对象调用__rmul__