try:...except...finally

try:
    print('try...')
    r = 10 / 0
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
finally:
    print('finally...')
print('END')

else:

记录错误logging

import logging

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e)

main()
print('END')

抛出异常raise

  • 抛出自定义异常
#定义异常
class DemoError(ValueError):
    pass

def demo(s):
    n = int(s)
    if n==0:
        raise DemoError('invalid value: %s' % s)
    return 10 / n

demo('0')
  • 抓到异常后记录,然后自己直接抛出原异常
def foo(s):
    n = int(s)
    if n==0:
        raise ValueError('invalid value: %s' % s)
    return 10 / n

def bar():
    try:
        foo('0')
    except ValueError as e:
        print('ValueError!')
        raise

bar()
posted on 2017-08-16 09:57  行走在云端的愚公  阅读(138)  评论(0编辑  收藏  举报