python错误

来源:互联网 发布:淘宝经营模式是什么 编辑:程序博客网 时间:2024/05/17 06:14

格式1:

try.....except 错误类型1,e:    print e    or raise....   except 错误类型2,e:    print e    raise...finally....例如:try:    print 'try...'    r = 10 / int('a')    print 'result:', rexcept ValueError, e:    print 'ValueError:', eexcept ZeroDivisionError, e:    print 'ZeroDivisionError:', eelse:    print 'no error!'finally:    print 'finally...'print 'END'说明:类型1一般要求是类型2的子类,错误类型都继承:BaseException

格式2:用logging来记录

import loggingdef foo(s):    return 10 / int(s)def bar(s):    return foo(s) * 2def main():    try:        bar('0')    except StandardError, e:        logging.exception(e)        logging.info(e)main()print 'END'

这里注意,在错误发生后被记录在logging里了,然后并且继续执行错误之后的语句(不包括错误所在的整体语句)

格式3:抛出错误

1:自定义错误

class FooError(StandardError):    passdef foo(s):    n = int(s)    if n==0:        raise FooError('invalid value: %s' % s)    return 10 / n

2.raise不带参数,原样抛出

def foo(s):    n = int(s)    return 10 / ndef bar(s):    try:        return foo(s) * 2    except StandardError, e:        print 'Error!'        raisedef main():    bar('0')main()

3.抛给父类和相关类

try:    10 / 0except ZeroDivisionError:    raise ValueError('input error!')

只要是合理的转换逻辑就可以,但是,决不应该把一个IOError转换成毫不相干的ValueError

4.常见错误类
ValueError
ZeroDivisionError
StandardError
IOError

5.断言assert

return 10/s
0 0
原创粉丝点击