异常

Python中异常可以通过try语句来检测,try语句有两种主要形式:try-except和try-finally。

def safe_float(object):
    try:
        retval = float(object)
    except (ValueError, TypeError):
        retval = 'argument must be a number or numeric string'
    return retval

所有异常之母的类叫BaseException,继承结构如下:

-BaseException
    |-KeyboardInterrupt
    |-SystemExit
    |-Exception
        |-(all other current built-in exceptions)
try:
    :
except Exception, e:
    # handle real errors

要捕获所有异常,则

try:
    :
except BaseException, e
    # handle all errors

异常参数

def safe_float(object):
    try:
        retval = float(object)
    except (ValueError, TypeError), diag:
        retval = str(diag)
    return retval

当try语句后带else语句时,在try范围内没有异常被检测到时,else语句才会执行。
finally语句是不论异常是否发生、是否被捕获都会被执行的一段代码。
try-finally语句常常用来维持一致的行为而无论异常是否发生。

try:
    ccfile = open('carddata.txt', 'r')
    txns = ccfile.readlines()
    ccfile.close()
except IOError:
    log.write('no txns this month\n')
try:
    try:
        ccfile = open('carddata.txt', 'r')
        txns = ccfile.readlines()
    except IOError:
        log.write('no txns this month\n')
finally:
        ccfile.close()

摘自《Python核心编程》

posted @ 2015-12-09 01:22  dflyingfish  阅读(122)  评论(0)    收藏  举报