AggregateException クラス

定義

アプリケーションの実行中に発生したエラーを表します。

public ref class AggregateException : Exception
public class AggregateException : Exception
[System.Serializable]
public class AggregateException : Exception
type AggregateException = class
    inherit Exception
[<System.Serializable>]
type AggregateException = class
    inherit Exception
Public Class AggregateException
Inherits Exception
継承
AggregateException
属性

次の例では、例外を AggregateException キャッチし、メソッドを Handle 呼び出して、その例外に含まれる各例外を処理します。 最初 task1 の変数で例をコンパイルして実行すると、例外を AggregateException 含む UnauthorizedAccessException オブジェクトが生成されます。 その行をコメントアウトし、2 番目 task1 の変数のコメントを解除し、この例をコンパイルして実行すると、例外を AggregateException 含む IndexOutOfRangeException オブジェクトが生成されます。

using System;
using System.IO;
using System.Threading.Tasks;

class Example
{
   static async Task Main(string[] args)
   {
      // Get a folder path whose directories should throw an UnauthorizedAccessException.
      string path = Directory.GetParent(
                              Environment.GetFolderPath(
                              Environment.SpecialFolder.UserProfile)).FullName;

      // Use this line to throw UnauthorizedAccessException, which we handle.
      Task<string[]> task1 = Task<string[]>.Factory.StartNew(() => GetAllFiles(path));

      // Use this line to throw an exception that is not handled.
      // Task task1 = Task.Factory.StartNew(() => { throw new IndexOutOfRangeException(); } );
      try
      {
          await task1;
      }
      catch (UnauthorizedAccessException ae)
      {
          Console.WriteLine("Caught unauthorized access exception-await behavior");
      }
      catch (AggregateException ae)
      {
          Console.WriteLine("Caught aggregate exception-Task.Wait behavior");
          ae.Handle((x) =>
          {
              if (x is UnauthorizedAccessException) // This we know how to handle.
              {
                  Console.WriteLine("You do not have permission to access all folders in this path.");
                  Console.WriteLine("See your network administrator or try another path.");
                  return true;
              }
              return false; // Let anything else stop the application.
          });
      }

      Console.WriteLine("task1 Status: {0}{1}", task1.IsCompleted ? "Completed," : "",
                                                task1.Status);
   }

   static string[] GetAllFiles(string str)
   {
      // Should throw an UnauthorizedAccessException exception.
      return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories);
   }
}
// The example displays the following output if the file access task is run:
//       You do not have permission to access all folders in this path.
//       See your network administrator or try another path.
//       task1 Status: Completed,Faulted
// It displays the following output if the second task is run:
//       Unhandled Exception: System.AggregateException: One or more errors occurred. ---
//       > System.IndexOutOfRangeException: Index was outside the bounds of the array.
//          at Example.<Main>b__0()
//          at System.Threading.Tasks.Task.Execute()
//          --- End of inner exception stack trace ---
//          at System.AggregateException.Handle(Func`2 predicate)
//          at Example.Main(String[] args)
open System
open System.IO
open System.Threading.Tasks

let getAllFiles str =
    // Should throw an UnauthorizedAccessException exception.
    System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories)

// Get a folder path whose directories should throw an UnauthorizedAccessException.
let path =
    let directory =
        Environment.SpecialFolder.UserProfile
        |> Environment.GetFolderPath
        |> Directory.GetParent
    directory.FullName

// Use this line to throw an exception that is not handled.
// let task1 = Task<string []>.Factory.StartNew(fun () -> raise (IndexOutOfRangeException()) )
let task1 = Task.Factory.StartNew(fun () -> getAllFiles (path))

let execute () =
    try
        task1.Wait()
    with
    | :? UnauthorizedAccessException -> printfn "Caught unauthorized access exception-await behavior"
    | :? AggregateException as ae ->
        printfn "Caught aggregate exception-Task.Wait behavior"

        ae.Handle (fun x ->
            match x with
            | :? UnauthorizedAccessException ->
                printfn "You do not have permission to access all folders in this path."
                printfn "See your network administrator or try another path."
                true
            | _ -> false)
    printfn $"""task1 Status: {if task1.IsCompleted then "Completed," else ""}{task1.Status}"""

execute ()

// The example displays the following output if the file access task is run:
//       You do not have permission to access all folders in this path.
//       See your network administrator or try another path.
//       task1 Status: Completed,Faulted
// It displays the following output if the second task is run:
//       Unhandled exception. System.AggregateException: One or more errors occurred. (Index was outside the bounds of the array.) (Index was outside the bounds of the array.)
//        ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
//          at Exception1.task1@19.Invoke()
//          at System.Threading.Tasks.Task`1.InnerInvoke()
//          at System.Threading.Tasks.Task.<>c.<.cctor>b__277_0(Object obj)
//          at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)   
//       --- End of stack trace from previous location ---
//          at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)   
//          at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
//          --- End of inner exception stack trace ---
//          at System.AggregateException.Handle(Func`2 predicate)
//          at <StartupCode$exception1>.$Exception1.main@()
Imports System.IO
Imports System.Threading.Tasks

Module Example
    Sub Main()
        ' Get a folder path whose directories should throw an UnauthorizedAccessException.
        Dim path As String = Directory.GetParent(
                                       Environment.GetFolderPath(
                                       Environment.SpecialFolder.UserProfile)).FullName

        ' Use this line to throw UnauthorizedAccessException, which we handle.
        Dim task1 = Task(Of String()).Factory.StartNew(Function() GetAllFiles(path))

        ' Use this line to throw an exception that is not handled.
        ' Task task1 = Task.Factory.StartNew(Sub() Throw New IndexOutOfRangeException() )
        Try
            task1.Wait()
        Catch ae As AggregateException
            ae.Handle(Function(x)
                          If TypeOf (x) Is UnauthorizedAccessException Then ' This we know how to handle
                              Console.WriteLine("You do not have permission to access all folders in this path.")
                              Console.WriteLine("See your network administrator or try another path.")
                              Return True
                          Else
                              Return False ' Let anything else stop the application.
                          End If
                      End Function)
        End Try

      Console.WriteLine("task1 Status: {0}{1}", If(task1.IsCompleted, "Completed,", ""), 
                                                task1.Status)
    End Sub

    Function GetAllFiles(ByVal str As String) As String()
        ' Should throw an UnauthorizedAccessException exception. 
        Return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories)
    End Function
End Module

注釈

AggregateException は、複数のエラーを 1 つのスロー可能な例外オブジェクトに統合するために使用されます。 これは、 タスク並列ライブラリ (TPL)Parallel LINQ (PLINQ) で広く使用されています。 詳細については、「例外処理」および「方法: PLINQ クエリの例外を処理する」を参照してください。 詳細については、.NET Matters ブログの 「例外の集計 」エントリを参照してください。

コンストラクター

AggregateException()

エラーを説明するシステム提供メッセージを使用して、AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(Exception[])

この例外の原因である内部例外への参照を使用して、AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(IEnumerable<Exception>)

この例外の原因である内部例外への参照を使用して、AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(SerializationInfo, StreamingContext)

シリアル化したデータを使用して、AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(String)

指定したメッセージでエラーを説明する AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(String, Exception)

指定したエラー メッセージおよびこの例外の原因となった内部例外への参照を使用して、AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(String, Exception[])

指定したエラー メッセージと、この例外の原因である内部例外への参照を使用して、AggregateException クラスの新しいインスタンスを初期化します。

AggregateException(String, IEnumerable<Exception>)

指定したエラー メッセージと、この例外の原因である内部例外への参照を使用して、AggregateException クラスの新しいインスタンスを初期化します。

プロパティ

Data

例外に関する追加のユーザー定義情報を提供する、キーと値のペアのコレクションを取得します。

(継承元 Exception)
HelpLink

この例外に関連付けられているヘルプ ファイルへのリンクを取得または設定します。

(継承元 Exception)
HResult

特定の例外に割り当てられているコード化数値である HRESULT を取得または設定します。

(継承元 Exception)
InnerException

現在の例外の原因となる Exception インスタンスを取得します。

(継承元 Exception)
InnerExceptions

現在の例外の原因となった Exception インスタンスの読み取り専用コレクションを取得します。

Message

例外を説明するメッセージを取得します。

Message

現在の例外を説明するメッセージを取得します。

(継承元 Exception)
Source

エラーの原因となるアプリケーションまたはオブジェクトの名前を取得または設定します。

(継承元 Exception)
StackTrace

呼び出し履歴で直前のフレームの文字列形式を取得します。

(継承元 Exception)
TargetSite

現在の例外がスローされたメソッドを取得します。

(継承元 Exception)

メソッド

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Flatten()

AggregateException インスタンスを 1 つの新しいインスタンスにフラット化します。

GetBaseException()

この例外の根本的な原因である AggregateException を返します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetObjectData(SerializationInfo, StreamingContext)

シリアル化したデータを使用して、AggregateException クラスの新しいインスタンスを初期化します。

GetObjectData(SerializationInfo, StreamingContext)

派生クラスでオーバーライドされた場合は、その例外に関する情報を使用して SerializationInfo を設定します。

(継承元 Exception)
GetType()

現在のインスタンスのランタイム型を取得します。

(継承元 Exception)
Handle(Func<Exception,Boolean>)

この AggregateException に含まれる各 Exception のハンドラーを呼び出します。

MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在の AggregateException の文字列表現を作成して返します。

events

SerializeObjectState
互換性のために残されています。

例外がシリアル化され、例外に関するシリアル化されたデータを含む例外状態オブジェクトが作成されたときに発生します。

(継承元 Exception)

適用対象

スレッド セーフ

パブリックメンバーとプロテクトメンバーはすべてスレッドセーフであり、複数の AggregateException スレッドから同時に使用できます。