【python学习笔记】Python异常处理raise、try...except、断言assert
2017-09-21 16:33
1121 查看
说明
写代码时,我们有时希望捕捉到程序异常但程序不退出,有时候不确定程序是否会异常,有时候希望自己定义异常,中断程序运行。异常处理raise
使用raise抛出异常,一旦执行了raise语句,raise后面的语句将不能执行。try: s = None if s is None: print "s None" raise NameError #如果引发NameError异常,后面的代码将不能执行 print len(s) except TypeError: print "None没有长度"
异常处理try….except
程序发生异常时,try….except捕获异常避免程序退出。可能发生错误的语句放在try模块里,用except来处理异常。except可以处理一个专门的异常,如果except后没有指定异常,则默认处理所有的异常。每一个try,都必须至少有一个except
# 不处理 a = 10 b = 'leason' c=a+b print 'over' result: Traceback (most recent call last): File "F:/gitHub/OrmCommand/app/test.py", line 17, in <module> c = a + b TypeError: unsupported operand type(s) for +: 'int' and 'str' # 处理 a = 10 b = 'leason' try: c = a + b print c except TypeError, e: print e.message print 'over' result: unsupported operand type(s) for +: 'int' and 'str' over
try ….except…else 语句,当没有异常发生时,else中的语句将会被执行。
try …finally语句, 无论异常是否发生,在程序结束前,finally中的语句都会被执行。
断言assert
在表达式expression1为假的时候,结束程序,抛出断言类错误(AssertionError: expresssion2),表达式expression2可有可无。*当然,如果expression为真的时候,什么都不做,继续往下执行。a = 888 assert type(a) == str,'a is type of int' result: Traceback (most recent call last): File "F:/gitHub/OrmCommand/app/test.py", line 20, in <module> assert type(a) == str,'a is type of int' AssertionError: a is type of int
并不是任何时候应用断言都是合适的,在Python中错误都有自己的类型,只有在自己不确定、或者怀疑会出错的时候用断言,或者在DEBUG时候用断言
leason | 个人博客
相关文章推荐
- Python异常处理——try...except、主动引发异常(raise)、断言(assert)
- Python学习笔记之错误处理(关键词:错误处理、异常机制、try、except、else、finally、raise)
- Python异常处理try...except...finally raise assert
- Python异常处理try...except...finally raise assert
- (Python)异常处理try...except、raise
- 【】Python】异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- Python_异常处理try...except、raise
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- python异常处理try,except,else,finally,raise
- python异常处理try,except,else,finally,raise
- Python异常处理try...except、raise
- Python异常处理try...except、raise
- python 对异常的处理(try...finally...和with 方法)- 千月的python linux 系统管理指南学习笔记(15)
- Python---异常处理try...except、raise
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- python异常图解:try、raise、except、else、finally块用法简要说明