python 捕获异常顺序

catch 异常的时候,有关的异常(若是抛出子类异常,则父类异常的except也算。反之不算)except的语句是按代码顺序执行,

也就是说,当一个异常发生时,从若干except中若遇见异常类基类,父类,自身则按照代码顺序,执行最早遇见的那个except语句。

异常类中变量调用顺序则是子类先从子类中找,找不到再往上层找,没有什么特别(下例会输出''hi'',而不是''boom'')。

如:

# -*- coding:utf-8 -*-


class MyException(Exception):
    def __init__(self):
        self.mes = 'err'
        self.msg = 'boom'

    def __str__(self):
        return self.msg


class LogoutError(MyException):
    def __init__(self):
        self.msg = 'hi'
        self.message = 'hello'


try:
    raise LogoutError
except Exception as e:
    print(e.msg)

except LogoutError as e:
    print(e.msg, 1111111)

会执行Excption中的语句。不会执行LogoutError语句。

output:

hi

猜你喜欢

转载自www.cnblogs.com/renxchen/p/10064857.html