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

发布时间 2023-04-04 16:45:27作者: itjeff

在日常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等。