Exception.InnerException 屬性

定義

取得造成目前例外狀況的 Exception 執行個體。

C#
public Exception InnerException { get; }
C#
public Exception? InnerException { get; }

屬性值

Exception

物件,描述造成目前例外狀況的錯誤。 InnerException 屬性會傳回與傳遞到 Exception(String, Exception) 建構函式中相同的值;如果沒有提供內部例外狀況值給建構函式,則傳回 null。 這個屬性是唯讀的。

實作

範例

下列範例示範擲回和攔截參考內部例外狀況的例外狀況。

C#
using System;

public class AppException : Exception
{
   public AppException(String message) : base (message)
   {}

   public AppException(String message, Exception inner) : base(message,inner) {}
}

public class Example
{
   public static void Main()
   {
      Example ex = new Example();

      try {
         ex.CatchInner();
      }
      catch(AppException e) {
         Console.WriteLine ("In catch block of Main method.");
         Console.WriteLine("Caught: {0}", e.Message);
         if (e.InnerException != null)
            Console.WriteLine("Inner exception: {0}", e.InnerException);
      }
   }

   public void ThrowInner ()
   {
      throw new AppException("Exception in ThrowInner method.");
   }

   public void CatchInner()
   {
      try {
         this.ThrowInner();
      }
      catch (AppException e) {
         throw new AppException("Error in CatchInner caused by calling the ThrowInner method.", e);
      }
   }
}
// The example displays the following output:
//    In catch block of Main method.
//    Caught: Error in CatchInner caused by calling the ThrowInner method.
//    Inner exception: AppException: Exception in ThrowInner method.
//       at Example.ThrowInner()
//       at Example.CatchInner()

備註

當擲回例外 X 狀況做為先前例外 Y 狀況的直接結果時,的 InnerException X 屬性應該包含 的 Y 參考。

您可以使用 InnerException 屬性來取得造成目前例外狀況的例外狀況集合。

您可以建立攔截先前例外狀況的新例外狀況。 處理第二個例外狀況的程式碼可以使用先前例外狀況中的其他資訊,更適當地處理錯誤。

假設有一個函式會讀取檔案,並將該檔案中的資料格式化。 在此範例中,當程式碼嘗試讀取檔案時, IOException 會擲回 。 函式會 IOException 攔截 ,並擲回 FileNotFoundExceptionIOException可以儲存在 的 FileNotFoundException 屬性中 InnerException ,讓攔截 FileNotFoundException 的程式碼檢查初始錯誤的原因。

屬性 InnerException 會保留內部例外狀況的參考,會在初始化例外狀況物件時設定。

適用於

產品 版本
.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
.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
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0