Python 错误处理

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013274257/article/details/84944189
# -*- coding:utf-8 -*-

import logging
from functools import reduce

try:
    print('try...')
    r = 10 / int('0')
    print('results:', r)
except ValueError as e:  # 检查类型是否正确
    print('ValueError:', e)
except ZeroDivisionError as e:  # 检查分母是否为0
    print('except:', e)
else:
    print('no error!')
finally:
    print('finally...')
print('END')


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


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


def maintest():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e)  # 使用logging报错之后后续程序将会继续执行


maintest()
print('Ending')


class FooError(ValueError):
    pass


def doo(d):
    n = int(d)
    if n == 0:
        raise ValueError('Invalid value: %s' % d)  # raise第二种抛出错误方法
    return 10 / n


def mar():
    try:
        doo('0')
    except ValueError as e:
        print('ValueError!')
        raise  # 获得错误信息后,raise如果不带参数,就会把当前错误原样抛出给上层


# mar()
def str2num(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except Exception as e:
            return 0


def calc(exp):
    ss = exp.split('+')
    ns = map(str2num, ss)
    return reduce(lambda acc, x: acc + x, ns)


def mains():
    r = calc('100 + 200 + 345')
    print('100 + 200 + 345 =', r)
    r = calc('99 + 88 + 7.6')
    print('99 + 88 + 7.6 =', r)


mains()
展开阅读全文

没有更多推荐了,返回首页