英語で読む

次の方法で共有


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がスローされた場合は、プロパティXInnerException参照をY含める必要があります。

InnerException プロパティを使用して、現在の例外の原因になった例外のセットを取得します。

以前の例外をキャッチする新しい例外を作成できます。 2 番目の例外を処理するコードでは、前の例外の追加情報を使用して、エラーをより適切に処理できます。

ファイルを読み取り、そのファイルからデータを書式設定する関数があるとします。 この例では、コードがファイルの読み取りを試みると、a IOException がスローされます。 この関数は、 .IOException FileNotFoundException これはIOException、最初のエラーの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