异常处理
- 格式:
try:
pass # 可能出现异常的代码
except:
pass # 如有try出现异常,走这里
else:
pass # 若未抛出异常, 走这里
finally:
# 常用于 close 文件、数据库 等 释放内存
pass # 无论有无异常,都执行(非必须)
- except
try:
raise Exception(ZeroDivisionError(' xxx error')) # 可能出现异常的代码
except ZeroDivisionError as e:
print('ZeroDivisionError', e) # 做出 对应的异常 处理
except ValueError:
print('ValueError') # 做出 对应的异常 处理
except Exception as err:
print(err)
# 未预见异常 总处理
except Exception: # 代码不可到达
print('Exception') # Exception 的全部 子类异常
finally:
print(' **** run end **** ')
自上往下匹配except 异常,
若把except Exception:放在前面,
后面的子类异常匹配不到。
- BaseException类
- Exception 类
- ZeroDivisionError
- ValueError
- 等等
- Exception 类
try 中声明的变量,无法再 except 或 finall 中处理:
stream = None
try:
stream = open('xx')
except:
pass
finally:
if stream:
stream.close()
特殊的return
def func():
try:
return 1
except:
return 2
finally:
return 3
f = func() # 无论什么情况,都执行finally,return 3
def func0():
try:
return 1
except:
return 2
finally:
pass
f = func0() # 无论什么情况,虽都执行finally,但仍return 1或2
finally 的 return 覆盖了 try 或 except 的 return
抛出异常 raise
raise Exception(ZeroDivisionError(' xxx error'))