常见的异常
BaseException
:所有异常的基类KeyboardInterrupt
:用户中断执行Exception
:常规错误的基类StandardError
:所有内建标准异常的基类ArithmeticError
:所有数值计算错误的基类AttributeError
:对象没有这个属性IOError
:输入/输出错误ImportError
:导入模块失败IndexError
:没有这个索引KeyError
:没有这个键NameError
:没有初始化这个对象RuntimeError
:运行错误SyntaxError
:语法错误IndentationError
:缩进错误TypeError
:对类型无效的操作ValueError
:传入无效的参数Warning
:所有警告的基类DeprecationWarning
:关于被弃用特征的警告FutureWarning
:关于构造将来语义会有改变的警告RuntimeWarning
:运行警告SyntaxWarning
:语法警告
异常的捕获
try
except
语句1
2
3
4
5
6
7
8
9
10
11
12import sys
try: # 尝试执行可能发生异常的语句
with open('myfile.txt', 'r', encoding='utf-8') as f:
s = f.readline()
i = int(s.strip())
except OSError as err: # 捕获输入输出错误
print('OS error: {}'.format(err))
except ValueError: # 捕获无效参数
print('Could not convert data to integer.')
except: # 捕获其它错误,并输出错误信息
print('Unexpected error:', sys.exc_info()[0])try
except
else
1
2
3
4
5
6
7try:
f = open('myfile.txt', 'r')
except IOError: # 发生异常时执行的代码
print('Can not open file.')
else: # 没有发生异常时执行的代码
print('File has {} lines'.format(len(f.readlines())))
f.close()finally
语句:无论是否发生异常都会执行1
2
3
4
5
6
7
8
9
10try:
f = open('myfile.txt', 'w', encoding='utf-8')
i = int(input('Please input something:'))
except ValueError:
print('Could not convert data to integer.')
else:
f.write(str(i))
finally:
print('Close file.')
f.close()
抛出异常
raise
语句1
2
3x = 2
if x > 1:
raise Exception('Invalid value: {}'.format(x))
自定义异常
异常的本质是一个类
1
2
3
4
5
6
7
8class MyError(Exception):
def __init__(self, value):
self.value = value
try:
raise MyError(5)
except MyError as e:
print('MyError occured, value: {}'.format(e.value))
日志模块
logging
模块用于处理日志logging.getLogger
:创建记录器logging.setLevel
:设置日志级别logging.FileHandler
:创建日志文件logging.StreamHandler
:将日志输出到控制台logging.Formatter
:设置日志格式addHandler
:将日志处理程序添加到记录器1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
fh = logging.FileHandler('debug.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
logger.info('info message')
logger.debug('debug message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
捕获异常并记录
1 | import logging |