3.异常处理代码示例(以代码为基础来归纳)
----------------------------------------------------------------------------------------------------------------------------------
# coding:utf8
'''
3.异常处理实例
'''
import time
from __builtin__ import IndentationError
##异常的用法 异常用IOError
try:
open('.txt','r')
except IOError:
print '----打开文件不存在,使用IOError'
##异常的用法 异常用NameError
try:
print a
except NameError:
print '----这里的name异常,变量没有定义,使用NameErrorn'
##异常的用法 异常用Exception
try:
print b
except Exception:
print '----这里的name异常,变量没有定义,使用Exception'
##异常的用法 异常用BaseException
try:
#print b
open('.txt','r')
except BaseException,msg: #加msg来打印出异常信息,多少行有问题
print '----这里的IO异常,使用BaseException'
print '----使用BaseException,打印msg信息为:',msg
##异常的用法 异常try-except加入else
try:
a=2
print '----try-except-else',a
except BaseException,msg:
print msg
else: #else语句只有在没有异常时候才会被执行
print '----try-except-else无异常信息'
##异常的用法 异常try-except加入finally
files=file("test.txt",'r')
strs=files.readlines()
try:
for i in strs:
print i
#time.sleep(1)
finally: #finally后的语句 一直都会执行
files.close()
print'有无异常都会执行'
##异常的用法 主动抛出异常raise 注意:raise只能用python中提供的异常类,不能用自定义的异常如aError
inputContent=raw_input('请输入内容:')
if inputContent=='y':
print '输入格式正确,无异常'
else:
raise IndentationError('格式错误') #raise 主动抛出异常 各种常用异常归纳信息
![](https://images0.cnblogs.com/blog/760511/201508/262250412348341.png)