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 catch하고 메서드를 Handle 호출하여 포함된 각 예외를 처리합니다. 첫 번째 task1 변수를 사용하여 예제를 컴파일하고 실행하면 예외가 AggregateException 포함된 UnauthorizedAccessException 개체가 생성됩니다. 해당 줄을 주석 처리하고, 두 번째 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 는 여러 오류를 throw 가능한 단일 예외 개체로 통합하는 데 사용됩니다. TPL(작업 병렬 라이브러리)PLINQ(병렬 LINQ)에서 광범위하게 사용됩니다. 자세한 내용은 예외 처리방법: PLINQ 쿼리의 예외 처리를 참조하세요. 자세한 내용은 .NET Matters 블로그의 예외 집계 항목을 참조하세요.

생성자

AggregateException()

오류를 설명하는 시스템 제공 메시지를 사용하여 AggregateException 클래스의 새 인스턴스를 초기화합니다.

AggregateException(Exception[])

이 예외의 원인인 내부 예외에 대한 참조를 사용하여 AggregateException 클래스의 새 인스턴스를 초기화합니다.

AggregateException(IEnumerable<Exception>)

이 예외의 원인인 내부 예외에 대한 참조를 사용하여 AggregateException 클래스의 새 인스턴스를 초기화합니다.

AggregateException(SerializationInfo, StreamingContext)

serialize된 데이터를 사용하여 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

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Flatten()

AggregateException 인스턴스를 단일한 새 인스턴스로 평면화합니다.

GetBaseException()

이 예외의 근본 원인인 AggregateException을 반환합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)

serialize된 데이터를 사용하여 AggregateException 클래스의 새 인스턴스를 초기화합니다.

GetObjectData(SerializationInfo, StreamingContext)

파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
Handle(Func<Exception,Boolean>)

AggregateException에 포함된 각 Exception에서 처리기를 호출합니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 AggregateException의 문자열 표현을 만들고 반환합니다.

이벤트

SerializeObjectState
사용되지 않습니다.

예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

적용 대상

스레드 보안

모든 공용 및 보호된 멤버 AggregateException 는 스레드로부터 안전하며 여러 스레드에서 동시에 사용할 수 있습니다.