Python,区分自定义异常

标签 python exception-handling

这里是 Python 的新手。有这个代码:

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"

我最初使用 raise "Negative Number!" 等,但很快发现这是旧的处理方式,您必须调用 Exception 类。现在它工作正常,但我如何区分我的两个异常?对于下面的代码,它正在打印“这是一个负数,但我们没有崩溃”。对此的任何指示都会很棒。谢谢!

最佳答案

如果您希望能够区分发生的异常类型,则需要创建自己的异常类。示例(我继承自 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"

关于Python,区分自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32523086/

相关文章:

python - 将前 N 行与 pandas 列中的当前行进行比较

android - 使用 SL4A 在 Python 中获取声音幅度

.net - 如何从线程中捕获异常?

Python:为什么我不能遍历列表?我的异常类很无聊吗?

ruby - 最佳实践 : Using system supplied or custom exceptions for error conditions in ruby?

python - 如何保存n-d numpy数组数据,下次快速读取?

python - Objective C 到 Python 序列化

exception - Camel : onException vs. 拦截SendToEndpoint

python - 当按下按钮时,python 脚本在 Raspberry Pi 上自动运行

java - 在 Java 中总是抛出相同的异常实例