AggregateException.Handle(Func<Exception,Boolean>) メソッド

定義

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

public:
 void Handle(Func<Exception ^, bool> ^ predicate);
public void Handle (Func<Exception,bool> predicate);
member this.Handle : Func<Exception, bool> -> unit
Public Sub Handle (predicate As Func(Of Exception, Boolean))

パラメーター

predicate
Func<Exception,Boolean>

各例外に対して実行する述語。 述語は、処理する Exception を引数として受け入れ、例外が処理されたかどうかを示すブール値を返します。

例外

predicate 引数が null です。

この AggregateException に含まれる例外は処理されませんでした。

通常、例外をキャッチAggregateExceptionする例外ハンドラーは、ループ (C#) またはFor Eachループ (Visual Basic では) を使用foreachして、コレクションInnerExceptions内の各例外を処理します。 代わりに、次の例では、 メソッドを Handle 使用して各例外を処理し、インスタンスではない CustomException 例外のみを再スローします。

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var task1 = Task.Run( () => { throw new CustomException("This exception is expected!"); } );

      try {
          task1.Wait();
      }
      catch (AggregateException ae)
      {
         // Call the Handle method to handle the custom exception,
         // otherwise rethrow the exception.
         ae.Handle(ex => { if (ex is CustomException)
                             Console.WriteLine(ex.Message);
                          return ex is CustomException;
                        });
      }
   }
}

public class CustomException : Exception
{
   public CustomException(String message) : base(message)
   {}
}
// The example displays the following output:
//        This exception is expected!
open System
open System.Threading.Tasks

type CustomException(message) =
    inherit Exception(message)

let task1 =
    Task.Run(fun () -> raise (CustomException "This exception is expected!"))

try
    task1.Wait()
with
| :? AggregateException as ae ->
    // Call the Handle method to handle the custom exception,
    // otherwise rethrow the exception.
    ae.Handle (fun ex ->
        if ex :? CustomException then
            printfn $"{ex.Message}"

        ex :? CustomException)

// The example displays the following output:
//        This exception is expected!
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim task1 = Task.Run(Sub() Throw New CustomException("This exception is expected!"))

      Try
         task1.Wait()
      Catch ae As AggregateException
         ' Call the Handle method to handle the custom exception,
         ' otherwise rethrow the exception.
         ae.Handle(Function(e)
                      If TypeOf e Is CustomException Then
                         Console.WriteLine(e.Message)
                      End If
                      Return TypeOf e Is CustomException
                   End Function)
      End Try
   End Sub
End Module

Class CustomException : Inherits Exception
   Public Sub New(s As String)
      MyBase.New(s)
   End Sub
End Class
' The example displays the following output:
'       This exception is expected!

ファイルを列挙するときに、 メソッドを Handle 使用して 特別な処理 UnauthorizedAccessException を提供する、より完全な例を次に示します。

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

public class Example2
{
    public static void Main()
    {
        // This should throw an UnauthorizedAccessException.
       try {
           var files = GetAllFiles(@"C:\");
           if (files != null)
              foreach (var file in files)
                 Console.WriteLine(file);
        }
        catch (AggregateException ae) {
           foreach (var ex in ae.InnerExceptions)
               Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
        }
        Console.WriteLine();

        // This should throw an ArgumentException.
        try {
           foreach (var s in GetAllFiles(""))
              Console.WriteLine(s);
        }
        catch (AggregateException ae) {
           foreach (var ex in ae.InnerExceptions)
               Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
        }
    }

    static string[] GetAllFiles(string path)
    {
       var task1 = Task.Run( () => Directory.GetFiles(path, "*.txt",
                                                      SearchOption.AllDirectories));

       try {
          return task1.Result;
       }
       catch (AggregateException ae) {
          ae.Handle( x => { // Handle an UnauthorizedAccessException
                            if (x is UnauthorizedAccessException) {
                                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 x is UnauthorizedAccessException;
                          });
          return Array.Empty<String>();
       }
   }
}
// The example displays the following output:
//       You do not have permission to access all folders in this path.
//       See your network administrator or try another path.
//
//       ArgumentException: The path is not of a legal form.
open System
open System.IO
open System.Threading.Tasks

let getAllFiles path =
    let task1 =
        Task.Run(fun () -> Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories))

    try
        task1.Result
    with
    | :? AggregateException as ae ->
        ae.Handle (fun x ->
            // Handle an UnauthorizedAccessException
            if x :? UnauthorizedAccessException then
                printfn "You do not have permission to access all folders in this path."
                printfn "See your network administrator or try another path."

            x :? UnauthorizedAccessException)

        Array.empty

// This should throw an UnauthorizedAccessException.
try
    let files = getAllFiles @"C:\"
    
    if not (isNull files) then
        for file in files do
            printfn $"{file}"
with
| :? AggregateException as ae ->
    for ex in ae.InnerExceptions do
        printfn $"{ex.GetType().Name}: {ex.Message}"

printfn ""

// This should throw an ArgumentException.
try
    for s in getAllFiles "" do
        printfn $"{s}"
with
| :? AggregateException as ae ->
    for ex in ae.InnerExceptions do
        printfn $"{ex.GetType().Name}: {ex.Message}"

// The example displays the following output:
//       You do not have permission to access all folders in this path.
//       See your network administrator or try another path.
//
//       ArgumentException: The path is empty. (Parameter 'path')
Imports System.IO
Imports System.Threading.Tasks

Module Example
    Public Sub Main()
        ' This should throw an UnauthorizedAccessException.
       Try
           Dim files = GetAllFiles("C:\")
           If files IsNot Nothing Then
              For Each file In files
                 Console.WriteLine(file)
              Next
           End If
        Catch ae As AggregateException
           For Each ex In ae.InnerExceptions
               Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
           Next
        End Try
        Console.WriteLine()

       ' This should throw an ArgumentException.
        Try
           For Each s In GetAllFiles("")
              Console.WriteLine(s)
           Next
        Catch ae As AggregateException
           For Each ex In ae.InnerExceptions
               Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
           Next
        End Try
        Console.WriteLine()
    End Sub

    Function GetAllFiles(ByVal path As String) As String()
       Dim task1 = Task.Run( Function()
                                Return Directory.GetFiles(path, "*.txt",
                                                          SearchOption.AllDirectories)
                             End Function)
       Try
          Return task1.Result
       Catch ae As AggregateException
          ae.Handle( Function(x)
                        ' Handle an UnauthorizedAccessException
                        If TypeOf x Is UnauthorizedAccessException Then
                            Console.WriteLine("You do not have permission to access all folders in this path.")
                            Console.WriteLine("See your network administrator or try another path.")
                        End If
                        Return TypeOf x Is UnauthorizedAccessException
                     End Function)
       End Try
       Return Array.Empty(Of String)()
    End Function
End Module
' The example displays the following output:
'       You do not have permission to access all folders in this path.
'       See your network administrator or try another path.
'
'       ArgumentException: The path is not of a legal form.

注釈

predicate 各呼び出しでは、 が処理されたかどうかを示す true または false が Exception 返されます。 すべての呼び出しの後、例外が未処理になった場合、すべての未処理の例外が新 AggregateException しいに配置され、スローされます。 それ以外の場合、メソッドは Handle 単に を返します。 の predicate 呼び出しで例外がスローされた場合、それ以上の例外の処理が停止され、スローされた例外は直ちにそのまま反映されます。

適用対象