Python: try/except 与 assert

异常捕获与断言

异常是针对程序中可能接收未被考虑到的输入(用户输入)导致程序无法进行正确处理而崩溃的情况。
在程序中进行异常捕获的目的是:希望程序能够顺利执行到结束,不希望程序在执行中崩溃。

断言是针对程序中由于变量被设置了错误的值(程序员编写)导致程序无法正常运行而崩溃的情况。
在程序中进行断言的目的是:希望程序中可能出现的问题快速暴露,程序尽早崩溃,给出警告,而不希望程序已经出错了却仍然继续执行到结束。

raise语句

使用raise语句抛出异常:

  • raise 关键字
  • Exception()接收一个字符串,包含需要传递的“出错提示信息”
  • Exception() 返回一个 Exception 对象,try/except可以捕获该对象
    例如:
>>> raise Exception('This is the error message.')
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    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 "<pyshell#26>", line 1, in <module>
    assert aFlag == True, 'Flag is False.'
AssertionError: Flag is False.

禁用断言

在 python3 和 .py 文件之前添加 -O 可以禁用 .py 文件中的断言。

python3 -O calc.py
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值