异常两种类型:
- 语法错误
- 逻辑错误
如何处理?
- 如果错误发生的情况是可以预知的,那么就可以使用流程控制进行预防处理
- 如果错误的发生条件不可预知,就可以使用 try。。。except。。 在错误发生时进行处理
Example1
n2 = 3
if isinstance(n2,int): #isinstance:判断是哪种类型
res = 10+n2
print(res)
Example2
try:
可能发生异常错误的代码
except:
如果发生异常则进入 except 代码块进行处理
假设读取的文件不存在,会发生错误。两种做法:
在文件读取前判断文件是否存在;
try。。。except 在错误发生时进行处理
try:
with open('./user.txt','r') as fp:
res = fp.read()
print(res)
except:
print('文件不存在')
print('程序的继续执行。。。')
- 通用异常类 Exception
S1=‘world’
try:
int(s1)
except Exception as e:
print('Exception====',e)
- 多分支异常类+通用异常类
s1 = 'hello'
try:
# int(s1) # ValueError
s1[5] # IndexError
except IndexError as e:
print('IndexError',e)
except KeyError as e:
print('KeyError',e)
except ValueError as e:
print('ValueError',e)
except Exception as e:
print('Exception',e)
- try。。。except。。。else
s1 = 'hello'
try:
str(s1)
except IndexError as e:
print('IndexError',e)
except ValueError as e:
print('ValueError',e)
except Exception as e:
print('Exception',e)
else:
print('try代码块中没有引发异常时,执行')
- try…except…else…finally
#finally无论是否引发异常都会执行,主要是用于执行清理工作
s1 = 'hello'
try:
int(s1)
print('如果前面的代码引发了异常,这个代码块将不在继续执行。。')
except IndexError as e:
print('IndexError',e)
except ValueError as e:
print('ValueError',e)
except Exception as e:
print('Exception',e)
else:
print('try代码块中没有引发异常时,执行')
finally:
print('无论是否引发了异常,都会执行这个代码块')
print('如果上面的代码有异常并且进行了处理,那么后面的代码将继续执行')
- 使用raise 主动抛出异常
try:
#可以使用 raise 主动抛出异常,并设置异常信息
raise Exception('发生错误')
except Exception as e:
print('Exception',e)
- assert 断言
assert1==1 #如果后面的表达式正确,则什么也不做
assert 2 == 1 # 如果后面的表达式错误,则直接抛出 AssertionError
自己定义异常
在出现异常后,对异常进行处理,并把异常写入日志
日志基本格式:
日期时间 异常的级别
异常信息
Logging
python的日志记录系统
class Myexception():
def __init__(self):
import traceback
import logging
# logging的基本配置
logging.basicConfig(
filename='./error.log',# 日志存储的文件及目录
format='%(asctime)s %(levelname)s \n %(message)s',# 格式化存储的日志格式
datefmt='%Y-%m-%d %H:%M:%S'
)
# 写入日志
logging.error(traceback.format_exc())
traceback回溯模块
logging 日志模块