AggregateException AggregateException AggregateException AggregateException Class

Definición

Representa uno o más errores que se producen durante la ejecución de una aplicación.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
Herencia
AggregateExceptionAggregateExceptionAggregateExceptionAggregateException
Atributos

Ejemplos

El ejemplo siguiente se detecta la AggregateException excepción y llama a la Handle método para controlar cada excepción contiene.The following example catches the AggregateException exception and calls the Handle method to handle each exception it contains. Compilar y ejecutar el ejemplo con la primera task1 variable debe tener como resultado un AggregateException objeto que contiene un UnauthorizedAccessException excepción.Compiling and running the example with the first task1 variable should result in an AggregateException object that contains an UnauthorizedAccessException exception. Marcar como comentario esa línea, el comentario de la segunda task1 variable y compilar y ejecutar el ejemplo produce una AggregateException objeto que contiene un IndexOutOfRangeException excepción.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

Comentarios

AggregateException se utiliza para consolidar varios errores en un objeto único y puede producir excepciones.AggregateException is used to consolidate multiple failures into a single, throwable exception object. Se usa ampliamente en el Task Parallel Library (TPL) y Parallel LINQ (PLINQ).It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). Para obtener más información, vea Control de excepciones y Cómo: Controlar excepciones en una consulta PLINQ.For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query. Para obtener más información, consulte el agregar excepciones entrada del blog de .NET Matters.For additional information, see the Aggregating Exceptions entry in the .NET Matters blog.

Constructores

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

Inicializa una nueva instancia de la clase AggregateException con un mensaje proporcionado por el sistema que describe el error.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[])

Inicializa una nueva instancia de la clase AggregateException que hace referencia a las excepciones internas que representan la causa de esta excepción.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>)

Inicializa una nueva instancia de la clase AggregateException que hace referencia a las excepciones internas que representan la causa de esta excepción.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)

Inicializa una nueva instancia de la clase AggregateException con datos serializados.Initializes a new instance of the AggregateException class with serialized data.

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

Inicializa una nueva instancia de la clase AggregateException con un mensaje especificado que describe el error.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)

Inicializa una nueva instancia de la clase AggregateException con el mensaje de error especificado y una referencia a la excepción interna que representa la causa de esta excepción.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[])

Inicializa una nueva instancia de la clase AggregateException con un mensaje de error especificado y referencias a las excepciones internas que representan la causa de esta excepción.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>)

Inicializa una nueva instancia de la clase AggregateException con un mensaje de error especificado y referencias a las excepciones internas que representan la causa de esta excepción.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.

Propiedades

Data Data Data Data

Obtiene una colección de pares clave-valor que proporcionan más información definida por el usuario sobre la excepción.Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

Obtiene la instancia Exception que produjo la excepción actual.Gets the Exception instance that caused the current exception.

(Inherited from Exception)
InnerExceptions InnerExceptions InnerExceptions InnerExceptions

Obtiene una colección de solo lectura de las instancias de Exception que causaron la excepción actual.Gets a read-only collection of the Exception instances that caused the current exception.

Message Message Message Message
Source Source Source Source

Devuelve o establece el nombre de la aplicación o del objeto que generó el error.Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

Obtiene una representación de cadena de los marcos inmediatos en la pila de llamadas.Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

Obtiene el método que produjo la excepción actual.Gets the method that throws the current exception.

(Inherited from Exception)

Métodos

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

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

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

Reduce las instancias de AggregateException a una sola instancia nueva.Flattens an AggregateException instances into a single, new instance.

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

Devuelve la excepción AggregateException que es la causa principal de esta excepción.Returns the AggregateException that is the root cause of this exception.

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

Sirve como la función hash predeterminada.Serves as the default hash function.

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

Inicializa una nueva instancia de la clase AggregateException con datos serializados.Initializes a new instance of the AggregateException class with serialized data.

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

Obtiene el tipo de tiempo de ejecución de la instancia actual.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>)

Invoca un controlador en cada objeto Exception contenido en esta excepción AggregateException.Invokes a handler on each Exception contained by this AggregateException.

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

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

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

Crea y devuelve una representación de cadena del objeto AggregateException actual.Creates and returns a string representation of the current AggregateException.

Eventos

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

Ocurre cuando una excepción se serializa para crear un objeto de estado de excepción que contenga datos serializados sobre la excepción.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

Se aplica a

Seguridad para subprocesos

Todos los miembros públicos y protegidos de AggregateException son seguros para subprocesos y se pueden usar simultáneamente desde varios subprocesos.All public and protected members of AggregateException are thread-safe and may be used concurrently from multiple threads.