AggregateException.Handle(Func<Exception,Boolean>) 메서드

정의

AggregateException에 포함된 각 Exception에서 처리기를 호출합니다.Invokes a handler on each Exception contained by this AggregateException.

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>

각 예외에 대해 실행할 조건자입니다.The predicate to execute for each exception. 조건자가 처리할 Exception을 인수로 수락하여 예외가 처리되었는지 나타내는 부울을 반환합니다.The predicate accepts as an argument the Exception to be processed and returns a Boolean to indicate whether the exception was handled.

예외

predicate 인수가 null입니다.The predicate argument is null.

AggregateException에 포함된 예외는 처리되지 않았습니다.An exception contained by this AggregateException was not handled.

예제

일반적으로 AggregateException 예외를 catch 하는 예외 처리기는 foreach 루프 (의 C#경우) 또는 For Each 루프 (Visual Basic)를 사용 하 여 해당 InnerExceptions 컬렉션의 각 예외를 처리 합니다.Ordinarily, an exception handler that catches an AggregateException exception uses a foreach loop (in C#) or For Each loop (in Visual Basic) to handle each exception in its InnerExceptions collection. 대신, 다음 예제에서는 Handle 메서드를 사용 하 여 각 예외를 처리 하 고 CustomException 인스턴스가 아닌 예외만 다시 throw 합니다.Instead, the following example uses the Handle method to handle each exception, and only re-throws exceptions that are not CustomException instances.

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!
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에 대 한 특수 처리를 제공 하는 보다 완전 한 예제입니다.The following is a more complete example that uses the Handle method to provide special handling for an UnauthorizedAccessException when enumerating files.

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

public class Example
{
    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.
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 처리 되었는지 여부를 나타냅니다.Each invocation of the predicate returns true or false to indicate whether the Exception was handled. 모든 호출 후 예외가 처리 되지 않은 경우 처리 되지 않은 모든 예외가 throw 되는 새 AggregateException에 배치 됩니다.After all invocations, if any exceptions went unhandled, all unhandled exceptions will be put into a new AggregateException which will be thrown. 그렇지 않으면 Handle 메서드는만 반환 합니다.Otherwise, the Handle method simply returns. predicate를 호출할 때 예외가 throw 되 면 예외 처리가 중단 되 고 throw 된 예외가 그대로 즉시 전파 됩니다.If any invocations of the predicate throws an exception, it will halt the processing of any more exceptions and immediately propagate the thrown exception as-is.

적용 대상