Python错误处理

  • 2020 年 11 月 11 日
  • 筆記
# -*- coding:utf-8 -*-
import logging

def testError(a):
    try:
        print("try...")
        r=10/int(a)
        print("[result]:%s"%r)
    except ValueError as e:
        print("ValueError:%s."%e)
        logging.exception(e)
    except ZeroDivisionError as e:
        print("ZeroDivisionError:%s."%e)
        logging.exception(e)
    else:
        print("no error.")
    finally:
        print("finally...")
    print("END")


def foo(a):
    return 100/int(a)

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

def crlf(c):
    try:
        print("try...")
        x=bar(c)
        print("result:%s."%x)
    except ValueError as e:
        print("ValueError:%s."%e)
        logging.exception(e)
    except ZeroDivisionError as e:
        print("ZeroDivisionError:%s."%e)
        logging.exception(e)
    finally:
        print("finally...")
    print("END")

class aooError(BaseException):
    def __init__(self,path):
        self.path=path

    def __str__(self):
        return self.path

    def __repr__(self):
        return self.path


def aoo(a):
    _a=int(a)
    if _a==0:
        raise aooError("this is error %s."%a)
    return 10/_a

def testAoo(a):
    try:
        print('try...')
        aoo(a)
    except aooError as e:
        print('------------',e)
        raise                     #非常关键
    finally:
        print("finally...")
    print('end')


if __name__=="__main__":
    # a=input()
    # testError(a)
    # print("---------------------")
    # crlf(a)

    a=input()
    testAoo(a)

 写的有点乱