异常捕获与断言
异常
是针对程序中可能接收未被考虑到的输入(用户输入)导致程序无法进行正确处理而崩溃的情况。
在程序中进行异常捕获的目的是:希望程序能够顺利执行到结束,不希望程序在执行中崩溃。
断言
是针对程序中由于变量被设置了错误的值(程序员编写)导致程序无法正常运行而崩溃的情况。
在程序中进行断言的目的是:希望程序中可能出现的问题快速暴露,程序尽早崩溃,给出警告,而不希望程序已经出错了却仍然继续执行到结束。
raise语句
使用raise语句抛出异常:
raise
关键字
Exception()
接收一个字符串,包含需要传递的“出错提示信息”
Exception() 返回一个 Exception 对象,
try/except
可以捕获该对象
例如:
>>> raise Exception('This is the error message.')
Traceback (most recent call last):
File "", line 1, in
raise Exception('This is the error message.')
Exception: This is the error message.
>>>
try/except语句
通常在函数定义中使用 raise 语句抛出异常,而由调用该函数的代码使用 try/except 语句对异常进行捕获并处理异常。
try/except
关键字
可能抛出异常的代码放在
try/except
之间
捕获的
Exception
对象保存在变量 err 中
例如:
>>> def aException():
raise Exception('This is a exception.')
>>> try:
aException()
except Exception as err:
print('An exception happened:' + str(err))
An exception happened:This is a exception.
>>>
Traceback信息写入日志文件
traceback.format_exc()
返回 Traceback 的字符串形式。
将 traceback 信息写入日志文件,可以方便调试。
>>> try:
aException()
except:
errorFile = open('errorInfo.txt','w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('Traceback info was written to errorInfo.txt')
162
Traceback info was written to errorInfo.txt
>>>
logging模块记录日志
尽量不要使用 print() 来调试,启用 logging 模块记录想要输出的调试信息。
logging.basicConfig()
设置输出信息的格式。
#! python3
import logging
logging.basicConfig(filename='factlogfile.txt',
level=logging.DEBUG,
format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
def factorial(n):
logging.debug('Start of factorial(%s)' % (n))
total = 1
for i in range(1, n + 1):
total *= i
logging.info("i is " + str(i) + ', total is ' + str(total))
logging.debug('End of factotial(%s)' % (n))
return total
################################
print(factorial(5))
设置 logging.basicConfig() 的 level 参数,使用相应的日志函数对感兴趣的日志信息分类输出:
DEBUG :最低级。
logging.debug()
INFO:一般信息。
logging.info()
WARNING:可能的问题,但程序不会因此崩溃。
logging.warning()
ERROR:程序可能崩溃。
logging.error()
CRITICAL:最高级,致命错误。
logging.critical()
>>> import logging
>>> logging.basicConfig(level = logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
>>> logging.debug('Some debugging details')
2020-03-09 14:41:02,603 - DEBUG - Some debugging details
>>> logging.info('Some debugging details')
2020-03-09 14:41:36,651 - INFO - Some debugging details
>>> logging.warning('Some debugging details')
2020-03-09 14:41:52,225 - WARNING - Some debugging details
>>> logging.error ('Some debugging details')
2020-03-09 14:42:14,634 - ERROR - Some debugging details
>>> logging.critical('Some debugging details')
2020-03-09 14:42:43,574 - CRITICAL - Some debugging details
禁用日志
向
logging.disable()
传入一个日志级别,它就会禁止该级别和更低级别的日志消息。
logging.disable(logging.ERROR)
assert语句
使用assert语句判断条件是否为期望状态:
assert
关键字
被判断的条件放在
assert
与
,
(逗号)之间
断言提示信息放在
,
(逗号)之后,条件为False时显示该信息
如果assert失败,程序就会崩溃,抛出AssertionError
>>> aFlag = True
>>> assert aFlag == True, 'Flag is False.'
>>> aFlag = False
>>> assert aFlag == True, 'Flag is False.'
Traceback (most recent call last):
File "", line 1, in
assert aFlag == True, 'Flag is False.'
AssertionError: Flag is False.
禁用断言
在 python3 和 .py 文件之前添加 -O 可以禁用 .py 文件中的断言。
python3 -O calc.py