示例
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)