python之异常

上一篇 / 下一篇  2013-10-22 11:07:43 / 个人分类:python

#异常:程序出现了错误而在正常控制流以外采取的行为。分为两阶段:首先是引发异常,发生错误  第二是检测阶段和采取可能的措施
#异常类型:1、nameError:尝试访问一个重未声明的变量,及没有初始化的变量
         #2、ZeroDivisionError:1/0除0异常,任何数值被0除都会有该异常
         #SyntaxError:python解释器语法错误,是一个唯一不在运行时发生的异常,表示代码有一个不正确的结构。在未改正之前,是不可以运行的。
         #IndexError:请求的所有超出序列范围
         #KeyError:请求一个不存在的字典关键字,字典是依靠字典字key访问数据值的,如果访问的key不存在就会抛出该异常
         #IOError:输入输出异常:尝试打开一个不存在的磁盘文件就会抛出该异常,
         #AttributeError:尝试访问未知的对象属性
#检测和处理异常 try- except- finally ,try -except -except:可以由多个except    ,try -finally:最后必要进行的清除工作 , try - except - else:处理没有探测到的异常

try:
    f = open("g://d.txt",'r')
except IOError,e:
    print 'could not open this file:',e    #could not open this file: [Errno 2] No such file or directory: 'g://d.txt'
#包装内建函数 :
def safe_float(obj):
    try :
        return float(obj)
    except ValueError:      #也可以一个except中写入多个异常    except (ValueError,TypeError),但是必须放到一个元组里面
        retval = 'cound not covert non-number to float'
    except TypeError:
        retval = 'object type cannot to be convert to float'
    except Exception ,e:        #捕获所有异常
        retval = "other exception"
    return retval
print safe_float('zd')
print safe_float(['za',112])
print safe_float('2234.3342')
print safe_float([])

try :
    f = open("g://d.txt",'r')
except SystemExit:
    raise
except Exception:
    pass
#在应用中封装使用的函数:
def safe_float(obj):
    'safe version of float()'
    try:
        retavl = float(obj)
    except (ValueError,TypeError),diag:
        retavl = str(obj)
    return retval
def main():
    "handles all the data processing"
    log = open('cardlog.txt','w')
    try:
        ccfile = open('cardlog.txt','r')
    except IOError,e:
        log.write("no txtms this month")
        log.close()
        return
    txns = ccfile.readlines()
    ccfile.close()
    total =0
    log.write("account log:\n")

    for eachtxn in txns:
        result = safe_float(eachtxn)
        if isinstance(result,folat):
            total += 1
            log.write('data....processed%s')
        else:
            log.write('ignored:%s'%result)
    print '$%.2f (new balance)'%total
    log.close()
if __name__ =='__main__':
    main()

#else语句:与在其他的情况下是一样的,如果在try范围中没有异常被检测到,就执行else语句
import rd_party_module
log = open('g://logfile.txt','r')
try :
    rd_party_module.function()
except :
    log.write("*** csaught exception in modle")
else:
    log.write("*** no exception caught")
#finally:异常处理中,放在最后,无论异常是否被触发,finnaly是最后必须被执行的。try-except /else  -finally
#   finally和try搭配; try - finally:不管异常是否被触发,finally都会被执行
try:
    ccfile = open('g://ca.txt')
    txns = ccfile.readlines()
    ccfile.close()
except IOError:
    log.write('no txns this month')
finally:
    ccfile.close()

#上下文管理
#with语句:try-exept try-finally :的一种特定的配合用法是保证共享的资源的唯一分配,并在结束任务时释放它。比如文件、线程资源、简单同步、数据库连接等。with就应用在这中常见
#用法:仅仅只能工作在支持上下文管理协议的对象,意味着只有内建了‘上下文管理’的对象才能使用with
    
with context_expr [as var]:
    with_suite
#例子:如果工作正常,会将文件对象赋值给f,然后对每一行进行操作,关闭文件。如果发生异常,会执行清理的代码,文件也会自动关闭
with open('g://c.txt','r') as f:
    for eachLine in f:
        #do ....something

#触发异常:前面的异常都是有解释器引发的,是执行期间的错误,程序可以通过raise触发异常
#断言assert:等价于布尔值的判定:当判定为假时引发异常.
assert 1==2 ,'one does not equal zero silly'
#断言在函数中实现是如下机制:传入一个表达式,如果该表达式为假,则抛出一个异常(__debug__默认为真)
def assert(expr,args = None):
    if __debug__ and not expr:
        raise AssertionError,args

#另一种获取异常信息方式:sys模块中的exc_info()函数,次功能提供了一个3元组的信息。多余我们用异常参数所获得的:exc_type:异常类  exc_value:异常类的实例  exc_traceback:跟踪记录
try:
    float('abc')
except :
    import sys
    exc_tuple = sys.exc_info()
print exc_tuple
for eachitem in exc_tuple:
    print eachitem


TAG:

yeziTesting的个人空间 引用 删除 yeziTesting   /   2013-10-22 11:08:54
学到了异常了,加油
 

评分:0

我来说两句

日历

« 2024-04-28  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 15375
  • 日志数: 25
  • 建立时间: 2013-07-27
  • 更新时间: 2013-10-22

RSS订阅

Open Toolbar