python-Exception使用

Exception异常自定义

#自定义异常类 ,MyInputExcp继承Exception异常
class MyInputExcp(Exception):
    def __init__(self, lenght, least):
        self.length = lenght
        self.least = least

try:
    #s = raw_input("python2请输入:\n")
    s = input("python3请输入:\n")
    if (len(s)<6):
        raise MyInputExcp(len(s),6) #强制异常
except MyInputExcp as x:
    print("发生异常,输入的长度为%d,长度应该大于等于%d"%(x.length,x.least))
else:
    print("无异常")
finally:
    print("不论异常都执行")

 

Exception异常的使用

def outputException(func):
    """
    修饰函数(函数发生异常输出)
    @param func:
    @return:
    """
    def inner(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as e:
            print(e)
            print('截图')
    return inner

 

posted @ 2020-07-21 10:36  南方的墙  阅读(343)  评论(0编辑  收藏  举报