python定制现有的内置异常

时间:2014-07-04 05:38:52

标签: python exception

例如,在此代码中,我希望以这种方式执行脚本行为。

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

如何实现?

try:
    a = [1,2]
    b = a[2]
except:
    raise something

2 个答案:

答案 0 :(得分:5)

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

这是有效的,因为sta [2]引发了一个IndexError。 a中只有2个元素,a [2]取第三个元素(从零开始计数)。

......好吧......

class YourCustomException(Exception):
    pass

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

答案 1 :(得分:0)

您应该阅读有关在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")