AggregateException Classe

Définition

Représente une ou plusieurs erreurs qui se produisent pendant l'exécution de l'application.

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
Héritage
AggregateException
Attributs

Exemples

L’exemple suivant intercepte l’exception AggregateException et appelle la Handle méthode pour gérer chaque exception qu’elle contient. La compilation et l’exécution de l’exemple avec la première task1 variable doivent entraîner un AggregateException objet qui contient une UnauthorizedAccessException exception. Commenter cette ligne, annuler le commentaire de la deuxième task1 variable et compiler et exécuter l’exemple produit un objet qui contient une AggregateException 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)
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

Remarques

AggregateException est utilisé pour consolider plusieurs échecs dans un objet d’exception levée unique. Il est utilisé en grande partie dans la bibliothèque parallèle de tâches (TPL) et Parallel LINQ (PLINQ). Pour plus d’informations, consultez Gestion des exceptions et Comment gérer des exceptions dans une requête PLINQ. Pour plus d’informations, consultez l’entrée Aggregating Exceptions dans le blog .NET Matters.

Constructeurs

AggregateException()

Initialise une nouvelle instance de la classe AggregateException avec un message fourni par le système qui décrit l'erreur.

AggregateException(Exception[])

Initialise une nouvelle instance de la classe AggregateException avec des références aux exceptions internes qui sont la cause de cette exception.

AggregateException(IEnumerable<Exception>)

Initialise une nouvelle instance de la classe AggregateException avec des références aux exceptions internes qui sont la cause de cette exception.

AggregateException(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe AggregateException avec des données sérialisées.

AggregateException(String)

Initialise une nouvelle instance de la classe AggregateException avec un message spécifié qui décrit l'erreur.

AggregateException(String, Exception)

Initialise une nouvelle instance de la classe AggregateException avec un message d'erreur spécifié et une référence à l'exception interne ayant provoqué cette exception.

AggregateException(String, Exception[])

Initialise une nouvelle instance de la classe AggregateException avec un message d'erreur spécifié et des références aux exceptions internes qui sont la cause de cette exception.

AggregateException(String, IEnumerable<Exception>)

Initialise une nouvelle instance de la classe AggregateException avec un message d'erreur spécifié et des références aux exceptions internes qui sont la cause de cette exception.

Propriétés

Data

Obtient une collection de paires clé/valeur qui fournissent des informations définies par l'utilisateur supplémentaires sur l'exception.

(Hérité de Exception)
HelpLink

Obtient ou définit un lien vers le fichier d'aide associé à cette exception.

(Hérité de Exception)
HResult

Obtient ou définit HRESULT, valeur numérique codée qui est assignée à une exception spécifique.

(Hérité de Exception)
InnerException

Obtient l'instance Exception qui a provoqué l'exception actuelle.

(Hérité de Exception)
InnerExceptions

Obtient une collection en lecture seule des instances Exception qui ont provoqué l'exception actuelle.

Message

Obtient un message qui décrit l'exception.

Message

Obtient un message qui décrit l'exception active.

(Hérité de Exception)
Source

Obtient ou définit le nom de l'application ou de l'objet qui est à l'origine de l'erreur.

(Hérité de Exception)
StackTrace

Obtient une représentation sous forme de chaîne des frames immédiats sur la pile des appels.

(Hérité de Exception)
TargetSite

Obtient la méthode qui lève l'exception actuelle.

(Hérité de Exception)

Méthodes

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
Flatten()

Aplanit des instances AggregateException dans une nouvelle instance unique.

GetBaseException()

Retourne AggregateException qui est la cause première de cette exception.

GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetObjectData(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la classe AggregateException avec des données sérialisées.

GetObjectData(SerializationInfo, StreamingContext)

En cas de substitution dans une classe dérivée, définit SerializationInfo avec des informations sur l'exception.

(Hérité de Exception)
GetType()

Obtient le type au moment de l'exécution de l'instance actuelle.

(Hérité de Exception)
Handle(Func<Exception,Boolean>)

Appelle un gestionnaire sur chaque Exception contenue dans cette AggregateException.

MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
ToString()

Crée et retourne une chaîne représentant la valeur AggregateException actuelle.

Événements

SerializeObjectState
Obsolète.

Se produit quand une exception est sérialisée pour créer un objet d'état d'exception qui contient des données sérialisées concernant l'exception.

(Hérité de Exception)

S’applique à

Cohérence de thread

Tous les membres publics et protégés de AggregateException sont thread-safe et peuvent être utilisés simultanément par plusieurs threads.