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}\n", ex.ToString()));
11                 
12           Console.WriteLine(string.Format("ex.Message. {0} \n", ex.Message));
13 
14         Console.WriteLine(string.Format("ex.StackTrace. {0} \n", ex.StackTrace));
15 
16           Console.WriteLine(string.Format("ex.Source. {0}.\n", ex.Source));
17 
18          Console.WriteLine(string.Format("ex.TargetSite. {0}.\n", 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等。

转载于:https://www.cnblogs.com/kushisei/p/6498473.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值