• Exception.ToString()使用及其他方法比较


     在日常C#的编码过程中,我们常常会使用try...catch...来抓住代码异常,并且在异常的时候打印log, 如下

    1             try
    2             {
    3             
    4              }
    5             catch (Exception e) 
    6             {
    7                 //输出Log信息等
    8                 throw;
    9             }                    

    而对于catch括号里的(Exception e),需要输出哪些感兴趣的信息呢?我在看别人代码的过程中,发现
    有的人会打印出e.Source,有的会打印出e.Message,有的会打印出e.StackTrace,而有的则直接打印
    e.ToString()。这几种打印方式哪种是比较合适的呢?为此楼主特地查看了MSDN对Exception各属性的解
    释,如下:

    属性:

    InnerException 获取导致当前异常的 Exception 实例。

    Message 获取描述当前异常的消息。

    Source 获取或设置导致错误的应用程序或对象的名称。

    StackTrace 获取调用堆栈上的即时框架字符串表示形式。

    TargetSite 获取引发当前异常的方法。

    方法:

    ToString() 创建并返回当前异常的字符串表示形式。(覆盖 Object.ToString()。)

    而具体结果是怎么样的呢,楼主特地写了个简单的程序来测试。

     1 private void TestException()
     2      {
     3        try
     4        {
     5           StackPanel P = null;
     6           Console.WriteLine("{0}",P.Width);
     7        }
     8       catch (System.Exception ex)
     9        {
    10           Console.WriteLine(string.Format("ex.ToString(). {0}
    ", ex.ToString()));
    11                 
    12           Console.WriteLine(string.Format("ex.Message. {0} 
    ", ex.Message));
    13 
    14         Console.WriteLine(string.Format("ex.StackTrace. {0} 
    ", ex.StackTrace));
    15 
    16           Console.WriteLine(string.Format("ex.Source. {0}.
    ", ex.Source));
    17 
    18          Console.WriteLine(string.Format("ex.TargetSite. {0}.
    ", ex.TargetSite));
    19        }
    20 }

    输出结果如图:

    由上可知,e.ToString()打印出来的信息是最全的,包括了e.Message,e.StackTrace,e.Source等信息。

    查看了一下MSDN上对于e.ToString()的实现,解释如下:

    The default implementation of ToString obtains the name of the class that threw the current
    exception, the message, the result of calling ToString on the inner exception, and the
    result of calling Environment.StackTrace. If any of these members is null, its value is not
    included in the returned string. If there is no error message or if it is an empty string
    (""), then no error message is returned. The name of the inner exception and the stack trace
    are returned only if they are not null.

    解释为:默认实现 ToString 获取引发当前异常、 消息、 调用的结果的类名称 ToString 对内部异常和
    调用的结果 Environment.StackTrace。 如果任何这些成员为 null,其值不包括在返回的字符串。如果没有任何错误消息,或者为空字符串 (""),则不返回任何错误消息。 仅当它们不是返回的内部异常
    和堆栈跟踪名称 null。

    综上所述,一般输出log的时候,只需调用ex.ToString()方法就可以得到完整的信息,包括e.Message,e.StackTrace,e.Source等信息,不需要另外调用e.Message,e.StackTrace,e.Source等。

  • 相关阅读:
    如何避免JavaScript的内存泄露及内存管理技巧
    【跟我一起学python吧】python chr()、unichr()和ord()
    阿里云,实力与担当并存!
    首届阿里白帽大会成功举办,用技术“肩天下”
    DataV数据可视化年度峰会——唤醒数据,看见未来
    支付宝移动端 Hybrid 解决方案探索与实践
    大数据上云第一课:(1)MaxCompute授权和外表操作躲坑指南
    函数计算支持应用中心功能
    Serverless 解惑——函数计算如何访问 MySQL 数据库
    开发函数计算的正确姿势——使用交互模式安装依赖
  • 原文地址:https://www.cnblogs.com/kushisei/p/6498473.html
Copyright © 2020-2023  润新知