转载请标明出处:
http://www.cnblogs.com/why168888/p/6435956.html本文出自:【Edwin博客园】
Python错误和异常概念(总)
1. 错误和异常的处理方式
1.常见的错误
- a:NameError
- if True:SyntaxError
- f = oepn('1.txt'):IOError
- 10/0:ZeroDivisionError
- a = int('d'):ValueError
- 程序运行中断:KeyboardInterrupt
2.Python-使用try_except处理异常(1)
try: try_suite except Exception [e]: exception_block
- try用来捕获try_suite中的错误,并且将错误交给except处理
- except用来处理异常,如果处理异常和设置捕获异常一致,使用exception_block处理异常
# case 1 try: undef except: print 'catch an except'
# case 2 try: if undef except: print 'catch an except'
- case1:可以捕获异常,因为是运行时错误
- case2:不能捕获异常,因为是语法错误,运行前错误
--
# case 3 try: undef except NameError,e: print 'catch an except',e
# case 4 try: undef except IOError,e: print 'catch an except',e
- case3:可以捕获异常,因为设置捕获NameError异常
- case4:不能捕获异常,因为设置IOError,不会处理NameError
Example
import random num = random.randint(0, 100) while True: try: guess = int(raw_input("Enter 1~100")) except ValueError, e: print "Enter 1~100" continue if guess > num: print "guess Bigger:", guess elif guess < num: print "guess Smaller:", guess elif guess == num: print "Guess OK,Game Over" break print '\n'
3. Python使用try_except处理异常(2)
- try-except:处理多个异常
try: try_suite except Exception1[e]: exception_block1 except Exception2[e]: exception_block2 except ExceptionN[e]: exception_blockN
4. Python-try_finally使用
try: try_suite finally: do_finally
- 如果try语句没有捕获错误,代码执行do_finally语句
- 如果try语句捕获错误,程序首先执行do_finally语句,然后将捕获的错误交给python解释器处理
5. Python-try-except-else-finally
try: try_suite except: do_except finally: do_finally
- 若try语句没有捕获异常,执行完try代码段后,执行finally
- 若try捕获异常,首先执行except处理错误,然后执行finally
6. Python-with_as语句
with context [as var]: with_suite
- with语句用来代替try_except_finall语句,使代码更加简洁
- context表达式返回是一个对象
- var用来保存context返回对象,单个返回值或者元祖
- with_suite使用var变量来对context返回对象进行操作
with语句实质是上下文管理:
- 上下文管理协议:包含方法
__enter__()
和__exit()__
,支持该协议的对象要实现这两个方法 - 上下文管理器:定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作
- 进入上下文管理器:调用管理器
__enter__
方法,如果设置as var语句,var变量接受__enter__()
方法返回值 - 退出上下文管理器:调用管理器
__exit__
方法
class Mycontex(object): def __init__(self, name): self.name = name def __enter__(self): print "__enter__" return self def do_self(self): print "do_self" def __exit__(self, exc_type, exc_val, exc_tb): print "__exit__" print "Error:", exc_type, " info:", exc_val if __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()
whith语句应用场景:
- 文件操作
- 进程线程之间互斥对象,例如互斥锁
- 支持上下文的其他对象
2. 标准异常和自动以异常
1. Python-assert和raise语句
- rais语句
- reise语句用于主动抛出异常
- 语法格式:raise[exception[,args]]
- exception:异常类
- args:描述异常信息的元组
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
- assert语句
- 断言语句:assert语句用于检测表达式是否为真,如果为假,引发AssertionError错误
- 语法格式:assert expression[,args]
- experession:表达式
- args:判断条件的描述信息
assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python-标准异常和自定义异常
- 标准异常
- python内建异常,程序执行前就已经存在
- 自定义异常:
- python允许自定义异常,用于描述python中没有涉及的异常情况
- 自定义异常必须继承Exception类
- 自定义异常只能主动触发
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.message try: raise CustomError('test CustomError') except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)
来源:https://www.cnblogs.com/why168888/p/6435956.html