Exception.ToString 方法

定義

建立並傳回目前例外狀況的字串表示。

C#
public override string ToString();

傳回

目前例外狀況的字串表示。

實作

範例

下列範例會造成例外狀況,並顯示在該例外狀況上呼叫 ToString 的結果。 請注意, Exception.ToString 當 Exception 類別實例出現在方法的 Console.WriteLine 引數清單中時,會隱含呼叫 方法。

C#
using System;

public class TestClass
{}

public class Example
{
   public static void Main()
   {
      var test = new TestClass();
      Object[] objectsToCompare = { test, test.ToString(), 123,
                                    123.ToString(), "some text",
                                    "Some Text" };
      string s = "some text";
      foreach (var objectToCompare in objectsToCompare) {
         try {
            int i = s.CompareTo(objectToCompare);
            Console.WriteLine("Comparing '{0}' with '{1}': {2}",
                              s, objectToCompare, i);
         }
         catch (ArgumentException e) {
            Console.WriteLine("Bad argument: {0} (type {1})",
                              objectToCompare,
                              objectToCompare.GetType().Name);
            Console.WriteLine("Exception information: {0}", e);
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//     Bad argument: TestClass (type TestClass)
//     Exception information: System.ArgumentException: Object must be of type String.
//        at System.String.CompareTo(Object value)
//        at Example.Main()
//
//     Comparing 'some text' with 'TestClass': -1
//
//     Bad argument: 123 (type Int32)
//     Exception information: System.ArgumentException: Object must be of type String.
//        at System.String.CompareTo(Object value)
//        at Example.Main()
//
//     Comparing 'some text' with '123': 1
//
//     Comparing 'some text' with 'some text': 0
//
//     Comparing 'some text' with 'Some Text': -1

備註

ToString 會傳回目前例外狀況的標記法,此例外狀況旨在供人類瞭解。 如果例外狀況包含區分文化特性的資料,則需要傳 ToString 回的字串標記法,才能考慮目前的系統文化特性。 雖然傳回字串的格式沒有確切的需求,但應該嘗試反映使用者所察覺的物件值。

的預設實 ToString 作會取得擲回目前例外狀況的類別名稱、訊息、在內部例外狀況上呼叫 ToString 的結果,以及呼叫 Environment.StackTrace 的結果。 如果其中任一成員為 null ,則傳回的字串中不包含其值。

如果沒有錯誤訊息,或它是空字串 (「」) ,則不會傳回任何錯誤訊息。 只有在不是 時 null ,才會傳回內部例外狀況和堆疊追蹤的名稱。

這個方法會覆寫 Object.ToString

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0