python知识-错误和异常

1.常见错误:

1)NameError

2)SyntaxError

3)IOError

4)ZeroDivisionError

5)ValueError


2.使用try-except处理异常

try:

    try_suite

except Exception [e]:

    exception_block

a.tyr用来捕获try_suite中的错误,并将错误交给except处理

b.except用来处理异常,如果处理异常和设置捕获异常一致,使用exception_block处理异常。如:

try:

    a

except NameError,e:

    print "catch Error:",e


print "exec over"

结果是:

catch Error: name 'a' is not defined
exec over


来看2个case

case 1:

try:

    undef

except:

    print "catch an except"

case 2:

try:

    if undef

except:

    print "catch an except"

case 1:可以捕获异常,因为是运行时出错

case 2:不能捕获异常,因为是语法错误,运行前出错


再来看2个case:

case 1:

try:

    undef

except NameError,e:

    print "catch an except",e

case 2:

try:

    undef

except IOError,e:

    print "catch an except",e

case 1:可以捕获异常,因为设置捕获NameError异常

case 2:不能捕获异常,因为设置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
    else:
        print "guess OK,game over"
        break
    print "\n"


3.使用try-except处理多个异常

try:

    try_suite

except Exception1 [e]:

    exception_block1

except Exception2 [e]:

    exception_block2

except ExceptionN [e]:

    exception_blockN


4.try-except--else使用

try:

    try_suite

except Exception1 [e]:

    exception_block1

else:

    none_exception


5.try--finally语句

try:

    try_suite

finally:

    do_finally

如果try语句没有捕获错误,代码执行do_finally语句

如果try语句捕获错误,程序首先执行do_finally语句,然后将捕获到的错误交给python解释器执行

规则:try-finally语句无论是否检测到异常,都会执行finally代码

作用:为异常处理事件提供清理机制,用来关闭文件或者释放系统资源

try:

    f=open("1.txt")

    print int(f.read())

finally:

    print "file close"

    f.close()


6.try-except-finally语句

try:

    try_suite

except:

    do_except

finally:

    do_finally

若try语句没有捕获异常,执行完try语句后执行finally

若try语句捕获到异常,首先执行except处理错误,然后执行finally


7.try-except-else-finally语句 

try:

    try_suite

except:

    do_except

else:

    do_else

finally:

    do_finally

若try语句没有捕获异常,执行完try代码块后,先执行完else的代码块,最后执行finally

若try语句捕获了异常,首先执行except处理错误,然后执行finally代码块


8.with语句
with context[as var]:

    with_suite

a.with语句是用来代替try-except-finally语句,使代码更加简洁

b.context表达式返回是一个对象

c.var用来保存context返回对象,单个返回值或者元组

d.with_suite使用var变量来对context返回对象进行操作

with open('1.txt') as f:

    print "in with f.read:",f.read()

print "with:",f.closed

说明:a.打开1.txt文件

b.f变量接收文件对象返回的对象

c.with中的代码执行完成后,关闭文件


with语句实质是山下文管理:

1)上下文管理协议:包含方法__enter__()和__exit__(),支持该协议的对象要实现这2个方法

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_value,traceback):
        print "__exit__"
        print "Error:",exc_type,"info:",exc_value

if __name__=='__main__':
    with Mycontex('C:\Users\lenovo\Desktop\work.txt') as f:
        print f.name
        f.do_self()

结果是:

__enter__
C:\Users\lenovo\Desktop\work.txt
do_self
__exit__
Error: None info: None

以下为错误的情况:

class Mycontex(object):
    def __init__(self,name):
        self.name=name
    def __enter__(self):
        print "__enter__"
        return self
    def do_self(self):
        print "do_self"
        a
    def __exit__(self,exc_type,exc_value,traceback):
        print "__exit__"
        print "Error:",exc_type,"info:",exc_value

if __name__=='__main__':
    with Mycontex('C:\Users\lenovo\Desktop\work.txt') as f:
        print f.name
        f.do_self()

结果是:

__enter__
C:\Users\lenovo\Desktop\work.txt
do_self
__exit__
Error: <type 'exceptions.NameError'> info: global name 'a' is not defined
Traceback (most recent call last):

File "F:/python代码/test1/test1.py", line 24, in <module>
File "F:/python代码/test1/test1.py", line 16, in do_self
NameError: global name 'a' is not defined


8.raise语句

用于语句主动抛出异常

raise [exception[,args]]

exception:异常类

args:描述异常信息的元组


9.assert语句

断言语句:assert语句用于检测表达式是否为真,如果为假,引发AssertionError错误

assert exception [,args]

exception:表达式

args:判断条件的描述信息

assert 7==6,'test assert'


10.标准异常和自定义异常

标准异常:python内建异常,程序执行前就已经存在

自定义异常:

1)python允许自定义异常,用于描述python中没有涉及到的异常情况

2)自定义异常必须继承Exception类

3)自定义异常只能主动触发

示例:

class FileError(IOError):

    pass

产生自定义异常:assert FileError,"file Error"


class CustomError(Exception):

    def __init__(self,info):

        Exception.__init__(self)

        self.errorinfo=info

    def __str__(self):

        return "CustomError:%s" % self.errorinfo

try:

    raise CustomError("test CustomError")

except CustomError,e:

    print "Errorinfo:%s" %(e)

结果是:

Errorinfo:CustomError:test CustomError

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值