• Python 2.7 Exception格式化工具


    首先说一个发现:

    1 try:
    2     抛错误,抛异常
    3 except Exception as e:
    4     都被这里抓住了
    5 except Error as e:
    6     这里啥事都没了


    然后,说说Exception as e的e。e可谓是格式五花八门。

    比如:

    再比如:

    这么不严谨的格式,实在没办法直接从e.Name或e.Message等之类的主流方式来一步到位地抓出ErrorTitle与ErrorDetail。那怎么办呢?进行了各种尝试后,发现个好方法:

    str(type(e)) 可以抓出Title,而且还包含Type。而str(e)则可以抓出Detail。

    因此,诞生了格式化工具:

    ExceptionX_Result.py:

    1 class ExceptionX_Result:
    2     exceptionType = None
    3     exceptionTitle = None
    4     exceptionDetail = None;

    ExceptionX.py:

     1 from ExceptionX_Result import ExceptionX_Result
     2 
     3 class ExceptionX:
     4 
     5     @staticmethod
     6     def ToString(arg_exception) : 
     7         result = ExceptionX_Result
     8         tempStr = str(type(arg_exception))
     9         tempStrArray = tempStr.split("'")
    10         result.exceptionTitle = tempStrArray[1]
    11         result.exceptionType = tempStrArray[0][1:]
    12         result.exceptionDetail = str(arg_exception)
    13         if result.exceptionDetail[0] == "<":
    14             if result.exceptionDetail[result.exceptionDetail.__len__() - 1] == ">" :
    15                 result.exceptionDetail = result.exceptionDetail[1:result.exceptionDetail.__len__() - 1]
    16         return result;

    用法例子:

    1 try:
    2     value = 1 / 0
    3 except Exception as e:
    4     #在下面这行下一个断点,然后看看tempExceptionInfo的结构吧~
    5     tempExceptionInfo = ExceptionX.ToString(e)


    呵呵,终于统一了。最终效果:

    再如:

  • 相关阅读:
    关于 Android 进程保活,你所需要知道的一切【转】
    android 按返回键最小化(后台运行)
    android notification完全解析【转】
    使用WakeLock使Android应用程序保持后台唤醒
    [Linux]Vim基本操作
    [STL]map的使用
    [python]使用python进行LINUX系统操作
    python challenge 2:迭代与列表
    python challenge 1、3:字符串处理
    python challenge 0:操作符与内建函数
  • 原文地址:https://www.cnblogs.com/xxxteam/p/3515590.html
Copyright © 2020-2023  润新知