AggregateException AggregateException AggregateException AggregateException Class

定义

表示在应用程序执行期间发生的一个或多个错误。Represents one or more errors that occur during application execution.

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

示例

下面的示例将捕获AggregateException异常, 并Handle调用方法来处理它包含的每个异常。The following example catches the AggregateException exception and calls the Handle method to handle each exception it contains. 使用第一个task1变量编译和运行示例时, 应生成一个AggregateException包含UnauthorizedAccessException异常的对象。Compiling and running the example with the first task1 variable should result in an AggregateException object that contains an UnauthorizedAccessException exception. 注释掉该行, 取消注释第二个task1变量, 编译并运行该示例将生成一个AggregateException包含IndexOutOfRangeException异常的对象。Commenting out that line, uncommenting the second task1 variable, and compiling and running the example produces an AggregateException object that contains an IndexOutOfRangeException exception.

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)
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用于将多个故障合并为单个 java.lang.throwable 的异常对象。AggregateException is used to consolidate multiple failures into a single, throwable exception object. 它广泛用于任务并行库 (TPL)并行 LINQ (PLINQ)It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). 有关详细信息,请参阅异常处理如何:处理 PLINQ 查询中的异常For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query. 有关其他信息, 请参阅 .NET 重要博客中的聚合异常条目。For additional information, see the Aggregating Exceptions entry in the .NET Matters blog.

构造函数

AggregateException() AggregateException() AggregateException() AggregateException()

使用由系统提供的用于描述错误的消息初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with a system-supplied message that describes the error.

AggregateException(Exception[]) AggregateException(Exception[]) AggregateException(Exception[]) AggregateException(Exception[])

用对作为此异常原因的内部异常的引用初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with references to the inner exceptions that are the cause of this exception.

AggregateException(IEnumerable<Exception>) AggregateException(IEnumerable<Exception>) AggregateException(IEnumerable<Exception>) AggregateException(IEnumerable<Exception>)

用对作为此异常原因的内部异常的引用初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with references to the inner exceptions that are the cause of this exception.

AggregateException(SerializationInfo, StreamingContext) AggregateException(SerializationInfo, StreamingContext) AggregateException(SerializationInfo, StreamingContext) AggregateException(SerializationInfo, StreamingContext)

用序列化数据初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with serialized data.

AggregateException(String) AggregateException(String) AggregateException(String) AggregateException(String)

使用指定的描述错误的消息初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with a specified message that describes the error.

AggregateException(String, Exception) AggregateException(String, Exception) AggregateException(String, Exception) AggregateException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with a specified error message and a reference to the inner exception that is the cause of this exception.

AggregateException(String, Exception[]) AggregateException(String, Exception[]) AggregateException(String, Exception[]) AggregateException(String, Exception[])

使用指定错误信息和对作为此异常原因的内部异常的引用来初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with a specified error message and references to the inner exceptions that are the cause of this exception.

AggregateException(String, IEnumerable<Exception>) AggregateException(String, IEnumerable<Exception>) AggregateException(String, IEnumerable<Exception>) AggregateException(String, IEnumerable<Exception>)

使用指定错误信息和对作为此异常原因的内部异常的引用来初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with a specified error message and references to the inner exceptions that are the cause of this exception.

属性

Data Data Data Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
InnerExceptions InnerExceptions InnerExceptions InnerExceptions

获取导致当前异常的 Exception 实例的只读集合。Gets a read-only collection of the Exception instances that caused the current exception.

Message Message Message Message

获取描述异常的消息。Gets a message that describes the exception.

Source Source Source Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(Inherited from Exception)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flatten() Flatten() Flatten() Flatten()

AggregateException 实例平展入单个新实例。Flattens an AggregateException instances into a single, new instance.

GetBaseException() GetBaseException() GetBaseException() GetBaseException()

返回 AggregateException,它是此异常的根本原因。Returns the AggregateException that is the root cause of this exception.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

用序列化数据初始化 AggregateException 类的新实例。Initializes a new instance of the AggregateException class with serialized data.

GetType() GetType() GetType() GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(Inherited from Exception)
Handle(Func<Exception,Boolean>) Handle(Func<Exception,Boolean>) Handle(Func<Exception,Boolean>) Handle(Func<Exception,Boolean>)

在每个由此 AggregateException 包含的 Exception 上调用处理程序。Invokes a handler on each Exception contained by this AggregateException.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

创建并返回当前 AggregateException 的字符串表示形式。Creates and returns a string representation of the current AggregateException.

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

适用于

线程安全性

的所有公共和受保护AggregateException的成员都是线程安全的, 可从多个线程并发使用。All public and protected members of AggregateException are thread-safe and may be used concurrently from multiple threads.