python04-错误、调试和测试
来源:互联网 发布:java后台接收上传图片 编辑:程序博客网 时间:2024/06/05 15:44
目录
- 目录
- 错误处理
- tryexceptfinally
- 抛出错误
- 调试
- print 和assert
- logging
- pdb
- IDE
- 单元测试
- 文档测试
1 错误处理
try…except…finally…
>>> try: print('try...') r=10/0 print('result:',r)except ZeroDivisionError as e: print('except:',e)finally: print('finally....') print('END')try...except: division by zerofinally....END
- 函数可能会抛出ValueError,所以我们用一个except捕获ValueError,用另一个except捕获ZeroDivisionError。
此外,如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句
>>> try: print('try...') r = 10 / int('a') print('result:', r)except ValueError as e: print('ValueError:', e)except ZeroDivisionError as e: print('ZeroDivisionError:', e)finally: print('finally...')try...ValueError: invalid literal for int() with base 10: 'a'finally...
- 常见的错误类型
- https://docs.python.org/3/library/exceptions.html#exception-hierarchy
- 使用try…except捕获错误还有一个巨大的好处,就是可以跨越多层调用
>>> def foo(s): return 10 / int(s)>>> def bar(s): return foo(s) * 2>>> def main(): try: bar('0') except Exception as e: print('Error:', e) finally: print('finally...')
抛出错误
- raise
>>> def a(m,n): if n==0: raise('the division is o') return m/n>>> a(10,2)5.0>>> a(10,0)Traceback (most recent call last): File "<pyshell#306>", line 1, in <module> a(10,0) File "<pyshell#304>", line 3, in a raise('the division is o')TypeError: exceptions must derive from BaseException>>> def aa(): try: a(10,0) except ValueError as e: print('ValuError!') raise>>> aa()Traceback (most recent call last): File "<pyshell#314>", line 1, in <module> aa() File "<pyshell#313>", line 3, in aa a(10,0) File "<pyshell#304>", line 3, in a raise('the division is o')TypeError: exceptions must derive from BaseException>>>
2 调试
print 和assert
- 方式简单粗暴
def foo(s): n = int(s) print('>>> n = %d' % n) return 10 / n
- 凡是用print()来辅助查看的地方,都可以用断言(assert)来替代- assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。如果断言失败,assert语句本身就会抛出AssertionError
def foo(s): n = int(s) assert n != 0, 'n is zero!' return 10 / ndef main(): foo('0')
logging
- 把print()替换为logging是第3种方式,和assert比,logging不会抛出错误,而且可以输出到文件
>>> import logging>>> logging.basicConfig(level=logging.INFO)>>> s='0'>>> n=int(s)>>> logging.info('n=%d' %n)INFO:root:n=0
pdb
IDE
- PyCharm
3 单元测试
4 文档测试
本学习笔记参考http://www.liaoxuefeng.com/
0 0
- python04-错误、调试和测试
- 错误、调试和测试
- 错误,调试和测试
- 错误、调试和测试
- 错误,调试和测试
- python错误、调试和测试
- python错误调试和测试
- Python错误、调试和测试
- python之错误、调试和测试
- Python学习----错误、调试和测试
- 【Python学习笔记】错误、调试和测试
- 学习笔记_错误、调试和测试
- Python之错误,调试和测试
- Python 的错误、调试和测试
- python04 变量和变量的命名
- 错误、调试、测试
- 错误、调试、测试
- python学习笔记(1)-错误处理、调试和测试
- 解决ADB not responding问题 Android studio
- mapreduce文档汇总
- itext setEncryption报错问题
- run reflection
- Android多线程问题。android.os.NetworkOnMainThreadException
- python04-错误、调试和测试
- Objective-C 和 Core Foundation 对象相互转换的内存管理总结
- <php+mysql>从PHP连接数据库,以及mysqli_connect()不能使用localhost的解答
- java *** 制作圣诞贺卡
- 基于栈和队列实现二叉树的遍历
- 请用fontAwesome代替网页icon小图标
- SVN提交版本时强制填写备注
- 数据结构课程设计之航空订票系统
- VelocityLayoutViewResolver和VelocityViewResolver的区别