Python自定义现有内置异常



例如,在这段代码中,我希望我的脚本行为是这样的:

当运行到b=a[2]时,或任何一行都会引发异常,无论异常是什么。我希望脚本停止,并引发一个定制的红色错误消息,如:"LOL!!"'

如何实现?

try:
    a = [1,2]
    b = a[2]
except:
    raise something
try:
    a = [1,2]
    b = a[2]
except IndexError:
    raise Exception('LOL!')

这可以工作,因为语句a[2]抛出一个IndexError。a中只有2个元素,a[2]取第三个元素(从0开始计数)。

…好吧…

class YourCustomException(Exception):
    pass
try:
    a = [1,2]
    raise YourCustomException('LOL')
except YourCustomException:
    print('NOW WHAT?')

您应该阅读有关在https://docs.python.org/2/reference/simple_stmts.html#raise引发异常的内容

异常层次结构为https://docs.python.org/2/library/exceptions.html#exception-hierarchy

这是你需要的答案,

try:
    a = [1,2]
    b = a[2]
#except Exception:
except IndexError: 
    raise Exception("Lol")

最新更新