python异常基础

"""
try后面至少要有一项,亦可以选择   /except/else/finally中的任意组合
assert语句一般用于开发时对程序条件的验证,只有当内置_debug_为True时,assert语句才有效。当Python脚本以-O选项编译成为字节码文件时,assert 语句将被移除。
except 带参数: 老版本的Python,except语句写作"except Exception, e",Python 2.6后应写作"except Exception as e"。 


AttributeError 调用不存在的方法引发的异常
EOFError     遇到文件末尾引发的异常
ImportError 导入模块出错引发的异常
IndexError     列表越界引发的异常
IOError     I/O操作引发的异常,如打开文件出错等
KeyError   使用字典中不存在的关键字引发的异常
NameError 使用不存在的变量名引发的异常
TabError 语句块缩进不正确引发的异常
ValueError 搜索列表中不存在的值引发的异常
ZeroDivisionError   除数为零引发的异常
"""

try:
    statment=1
    assert statement==0
    statement=2
    raise Exception
except Exception:
    statement="cautht error or exception in this branch, yet that error of this kind happens"
except TypeError:
    statement="cautht error or exception in this branch, yet that error of this kind happens"
except IndexError,Error:
    statement="cautht mutil error,any one of the errors happers,this branch would run"
except Exception,e:
    print e
    statement="e is the args of exception, give more detail of exception"    
except:
    statement="caught all kinds of error"
    traceback.print_exc()
else:
    statement_else="if no error occur,this statement would run"
    #这句话通常不是必须的,因为可以将 这句话放在可能触发的异常的语句之后,如果没有异常这句话同样会执行
finally:
    statement_finally="always run"
    #不管异常发不发生,这句话总要执行, 歧义在于,这与直接放在最后面执行的语句有什么区别?
    #这个在于提示作用,如果有异常出现,放在后面的语句将执行不了,那么try...体重的finally仍然可以执行
 
print statement




try:
    "do something"
finally:
    "tear things down"


"set things up可以是打开一个文件,tear things down为关闭文件。try-finally语句保证tear things down总被执行,即使do something抛出异常。"


# 然而如果要经常性的对文件进行操作,可以将其写成库函数,例如:
def controlled_execution(callback):
    "set things up"
    try:
        callback(thing)
    finally:
        "tear things down"

def my_function(thing):
    "do something"

controlled_execution(my_function)


# 需要不同功能时,需要定义新函数,然后传入controlled_execution,稍微有些繁琐。 
# 通过with,进一步简化上述操作。
class controlled_execution:
    def __enter__(self):
        "set things up"
        return thing
    def __exit__(self, type, value, traceback):
        "tear things down"

with controlled_execution() as thing:
    "some code"
    
# with语句,执行controlled_execution中的__enter__方法,做相应的准备工作,并将返回值付给as后变量,即thing。 
# 执行代码体,不论代码体是否发生异常,都会执行controlled_execution中的__exit__方法进行收尾工作。




# 另外__exit__可以通过返回true来抑制异常传播。例如,吞下类型错误异常,放行其它异常。

def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)






class controlled_execution:
    def __enter__(self):
        print "starting with block"
        return self
    
    def __exit__(self, type, value, traceback):
        print "exited normally"
        
    def message(self, args):
        print 'running'
        print args
        
with controlled_execution() as action:
    action.message("test")


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值