时间:2021-07-01 10:21:17 帮助过:69人阅读
1. 错误和异常的处理方式
a:NameError
if True:SyntaxError
f = oepn('1.txt'):IOError
10/0:ZeropisionError
a = int('d'):ValueError
程序运行中断:KeyboardInterrupt
try:
try_suite
except Exception [e]:
exception_blocktry用来捕获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',ecase3:可以捕获异常,因为设置捕获NameError异常
case4:不能捕获异常,因为设置IOError,不会处理NameError
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'try-except:处理多个异常
try:
try_suite
except Exception1[e]:
exception_block1
except Exception2[e]:
exception_block2
except ExceptionN[e]:
exception_blockNtry:
try_suite
finally:
do_finally如果try语句没有捕获错误,代码执行do_finally语句
如果try语句捕获错误,程序首先执行do_finally语句,然后将捕获的错误交给python解释器处理
try:
try_suite
except:
do_except
finally:
do_finally若try语句没有捕获异常,执行完try代码段后,执行finally
若try捕获异常,首先执行except处理错误,然后执行finally
with context [as var]:
with_suitewith语句用来代替try_except_finall语句,使代码更加简洁
context表达式返回是一个对象
var用来保存context返回对象,单个返回值或者元祖
with_suite使用var变量来对context返回对象进行操作
上下文管理协议:包含方法__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()文件操作
进程线程之间互斥对象,例如互斥锁
支持上下文的其他对象
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'
标准异常
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)更多Python错误和异常概念相关文章请关注PHP中文网!