zoukankan      html  css  js  c++  java
  • 异常

    from abc import *
    
    # 思路:遇到异常后、从异常字典匹配异常,匹配到了:调用匹配到的异常处理函数进行结果处理
    # 没匹配到,注册一个异常子类
    
    # key: 异常类型   value:msg
    exist_exception_dict = {'Nobody': 'BodyNoneFunc','BodyNotJson':"BodyNotJsonFunc"}
    
    # 自定义异常类
    class MyException(Exception): def __init__(self, msg=''): self.msg = msg def BodyNoneFunc(self): print('没有body体应该做哪些操作。。。') def BodyNotJsonFunc(self): print('body不是json格式应该做哪些操作。。。') def UserDefineException(name, msg=''): if name in exist_exception_dict: print('有该异常类 执行异常') getattr(MyException(),exist_exception_dict[name])() else: # 没有该异常 # 1.添加到异常字典 exist_exception_dict[name] = msg class_dict = {'msg': msg} # 2. 创建异常子类,并继承MyException setattr(MyException, name, '') type(name, (MyException,), class_dict) print('MyException所有子类', MyException.__subclasses__())
    import json
    
    def JsonDecodeErrorFun():
        print('必须是json格式 JsonDecodeErrorFunc')
    
    exceptionPool = {
        json.JSONDecodeError:JsonDecodeErrorFun,
    
    }
    
    def Do(fn,*params):
        try:
            fn(*params)
            print('0没异常')
            return True
    
        except Exception as e:
            print('有异常',e)
            if e in exceptionPool:
                print('在异常池')
                return exceptionPool[e]()
            print('不在异常池')
            return False
    
    
    
    Do(json.loads,111)
    # 使用
    from kunpengException import UserDefineException,exist_exception_dict, MyException
    import json
    
    
    
    
    body = 123
    try:
        UserDefineException('BodyNotJson1', 'body体必须是json')  # para: 异常类名,msg
        print(2222,MyException.__subclasses__())
        json.loads(body)
        print('BodyNotJson' in 1)
        print(111111,type(MyException.__dict__))
    
        raise kunpengException.BodyNotJson1
    
    
    except kunpengException.BodyNotJson1 as e:
        print(e)
    
    print('
     except_dict 字典:', exist_exception_dict)
    # 使用
    from kunpengException import UserDefineException, exist_exception_dict
    
    body = {}
    
    
    if not body:
        UserDefineException('Nobody11','body不能为空')# para: 异常类名,msg
    
    
    
    print('
     except_dict 字典:',exist_exception_dict )
  • 相关阅读:
    c盘瘦身、windows解除上网限速、贴膜注意事项
    windows7导入k8s用户证书
    ubuntu报错解决和注意事项
    ubuntu默认root密码问题,第一次使用ubuntu需要设置root密码
    java程序员修炼之道
    选择器代码
    css的使用技巧资料
    移动开发的相关资料
    使用phantomjs生成网站快照
    PHP Simple HTML DOM Parser Manual-php解析DOM
  • 原文地址:https://www.cnblogs.com/dingyunfeng/p/13022927.html
Copyright © 2011-2022 走看看