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等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM