码迷,mamicode.com
首页 > Web开发 > 详细

Python错误和异常概念

时间:2017-02-27 18:47:57      阅读:387      评论:0      收藏:0      [点我收藏+]

标签:

本文和大家分享的主要是python中常见的错误与异常及其相关处理方式,一起来看看吧,希望对大家学习python有所帮助。
1. 错误和异常的处理方式
1.常见的错误
1. aNameError
2. if TrueSyntaxError
3. f = oepn(’1.txt’)IOError
4. 10/0ZeroDivisionError
5. a = int(’d’)ValueError
6. 程序运行中断:KeyboardInterrupt
2.Python-使用try_except处理异常(1)
try:
try_suiteexcept Exception [e]:
exception_block
1. try用来捕获try_suite中的错误,并且将错误交给except处理
2. except用来处理异常,如果处理异常和设置捕获异常一致,使用exception_block处理异常
# case 1try:
undefexcept:
print ’catch an except’
# case 2try:
if undefexcept:
print ’catch an except’
· case1:可以捕获异常,因为是运行时错误
· case2:不能捕获异常,因为是语法错误,运行前错误
--
# case 3try:
undefexcept NameError,e:
print ’catch an except’,e
# case 4try:
undefexcept 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_suiteexcept Exception1[e]:
exception_block1except Exception2[e]:
exception_block2except ExceptionN[e]:
exception_blockN
4. Python-try_finally使用
try:
try_suitefinally:
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语句实质是上下文管理:
1. 上下文管理协议:包含方法 __enter__()  __exit()__ ,支持该协议的对象要实现这两个方法
2. 上下文管理器:定义执行with语句时要建立的运行时上下文,负责执行with语句块上下文中的进入与退出操作
3. 进入上下文管理器:调用管理器 __enter__ 方法,如果设置as var语句,var变量接受 __enter__() 方法返回值
4. 退出上下文管理器:调用管理器 __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语句应用场景:
1. 文件操作
2. 进程线程之间互斥对象,例如互斥锁
3. 支持上下文的其他对象
2. 标准异常和自动以异常
1. Python-assertraise语句
· 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)
来源:博客园

Python错误和异常概念

标签:

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
jiangjie190
加入时间:2016-02-19
  关注此人  发短消息
文章分类
jiangjie190”关注的人------(0
jiangjie190”的粉丝们------(0
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!