异常处理
- 异常就是错误
- 异常会导致程序崩溃并停止运行
- python能监控并捕获到异常,将异常部位的程序进行修理使得程序继续正常运行
try:
<代码块1>#被try关键字检查并保护的业务代码
except:#<异常的类型>
<代码块2> #代码块1出现错误后执行的代码块
# -*- coding: utf-8 -*-
def upper(str_data):# 小写变大写
new_str = str_data.upper()
return new_str
result = upper("gpc")
print(result)
# -*- coding: utf-8 -*-
def upper(str_data):# 小写变大写
new_str = ""
try:
new_str = str_data.upper()
except:
print("程序出错")
return new_str
result = upper(1111)
print(result)
捕获通用异常
- 无法确定是那种异常的情况下使用的捕获方法
# -*- coding: utf-8 -*-
def upper(str_data):# 小写变大写
new_str = ""
try:
new_str = str_data.upper()
except Exception as e:
print("程序出错:{}".format(e))
return new_str
result = upper(1111)
print(result)
捕获具体异常
- 确定是那种异常的情况下使用的捕获方法