python 异常

示例

try:
    pass
except (Exception, OverflowError, AttributeError): #捕获多个异常
    print("发生了异常执行")
    pass
else:
    print("没发生异执行")
    pass
finally:
    print("finally")
    pass

触发异常

raise Exception("异常发生了", 0)

# 实例
level = 0
try:
    if level < 1:
        raise (Exception, "Invalid level!")
except (Exception, err):
    print(1, err)
else:
    print(2)

用户自定义异常

定义异常

class Networkerror(Exception):
    def __init__(self, arg):
        self.args = arg

使用异常

try:
    raise Networkerror("Bad hostname")
except (Networkerror, e):
    print(e.args)
上一篇:异常处理的其它内容


下一篇:阿里大佬带你解获 Python With 关键字和语句之间的奥秘