Python,区分自定义异常

时间:2015-09-11 12:02:54

标签: python exception-handling

这里的Python相当新。有这个代码:

readThisCell()

我最初使用def someFunction( num ): if num < 0: raise Exception("Negative Number!") elif num > 1000: raise Exception("Big Number!") else: print "Tests passed" try: someFunction(10000) except Exception: print "This was a negative number but we didn't crash" except Exception: print "This was a big number but we didn't crash" else: print "All tests passed and we didn't crash" 等,但很快发现这是旧的做法,你必须调用Exception类。现在它工作正常,但我如何区分我的两个例外?对于下面的代码,它打印“这是一个负数,但我们没有崩溃”。对此的任何指示都会很棒。谢谢!

1 个答案:

答案 0 :(得分:11)

如果您希望能够区分发生的异常类型,则需要创建自己的异常类。示例(我继承自ValueError,因为我认为这是你最接近你想要的东西 - 如果区别无关紧要,它还允许你抓住ValueError

class NegativeError(ValueError):
    pass

class BigNumberError(ValueError):
    pass

def someFunction( num ):
    if num < 0:
        raise NegativeError("Negative Number!")
    elif num > 1000:
        raise BigNumberError("Big Number!")
    else:
        print "Tests passed"

try:
    someFunction(10000)
except NegativeError as e:
    print "This was a negative number but we didn't crash"
    print e
except BigNumberError as e:
    print "This was a big number but we didn't crash"
    print e
else:
    print "All tests passed and we didn't crash"