AggregateException Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
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
- 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. Le commentaire de cette ligne, la décompression de la deuxième task1 variable et la compilation et l’exécution de l’exemple produisent un AggregateException objet qui contient une 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)
{
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 en un seul objet d’exception levée. Il est largement utilisé dans la bibliothèque parallèle de tâches (TPL) et Parallel LINQ (PLINQ) . Pour plus d’informations, consultez Gestion des exceptions et Guide pratique pour gérer les exceptions dans une requête PLINQ. Pour plus d’informations, consultez l’entrée Aggregating Exceptions dans le blog .NET Matters.
Constructeurs
| Nom | Description |
|---|---|
| AggregateException() |
Initialise une nouvelle instance de la AggregateException classe avec un message fourni par le système qui décrit l’erreur. |
| AggregateException(Exception[]) |
Initialise une nouvelle instance de la AggregateException classe avec des références aux exceptions internes qui sont la cause de cette exception. |
| AggregateException(IEnumerable<Exception>) |
Initialise une nouvelle instance de la AggregateException classe avec des références aux exceptions internes qui sont la cause de cette exception. |
| AggregateException(SerializationInfo, StreamingContext) |
Obsolète.
Initialise une nouvelle instance de la classe AggregateException avec des données sérialisées. |
| AggregateException(String, Exception) |
Initialise une nouvelle instance de la AggregateException classe avec un message d’erreur spécifié et une référence à l’exception interne qui est la cause de cette exception. |
| AggregateException(String, Exception[]) |
Initialise une nouvelle instance de la AggregateException classe avec un message d’erreur spécifié et fait référence aux exceptions internes à la cause de cette exception. |
| AggregateException(String, IEnumerable<Exception>) |
Initialise une nouvelle instance de la AggregateException classe avec un message d’erreur spécifié et fait référence aux exceptions internes à la cause de cette exception. |
| AggregateException(String) |
Initialise une nouvelle instance de la AggregateException classe avec un message spécifié qui décrit l’erreur. |
Propriétés
| Nom | Description |
|---|---|
| Data |
Obtient une collection de paires clé/valeur qui fournissent des informations supplémentaires définies par l’utilisateur 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 affecté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 Exception instances qui ont provoqué l’exception actuelle. |
| Message |
Obtient un message qui décrit l’exception. |
| Message |
Obtient un message qui décrit l’exception actuelle. (Hérité de Exception) |
| Source |
Obtient ou définit le nom de l’application ou de l’objet qui provoque l’erreur. (Hérité de Exception) |
| StackTrace |
Obtient une représentation sous forme de chaîne des images immédiates 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
| Nom | Description |
|---|---|
| Equals(Object) |
Détermine si l’objet spécifié est égal à l’objet actuel. (Hérité de Object) |
| Flatten() |
Aplatit une AggregateException instance en une seule nouvelle instance. |
| GetBaseException() |
Retourne la Exception cause racine de cette exception. Cette exception est l’exception racine ou la première AggregateException qui contient plusieurs exceptions internes ou aucune exception interne du tout. |
| GetHashCode() |
Sert de fonction de hachage par défaut. (Hérité de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsolète.
Initialise une nouvelle instance de la classe AggregateException avec des données sérialisées. |
| GetType() |
Obtient le type d’exécution de l’instance actuelle. (Hérité de Exception) |
| Handle(Func<Exception,Boolean>) |
Appelle un gestionnaire sur chaque Exception contenu de ce AggregateException. |
| MemberwiseClone() |
Crée une copie superficielle du Objectactuel. (Hérité de Object) |
| ToString() |
Crée et retourne une représentation sous forme de chaîne de l’élément actif AggregateException. |
Événements
| Nom | Description |
|---|---|
| SerializeObjectState |
Obsolète.
Se produit lorsqu’une exception est sérialisée pour créer un objet d’état d’exception qui contient des données sérialisées sur l’exception. (Hérité de Exception) |
S’applique à
Cohérence de thread
Tous les membres publics et protégés sont AggregateException thread-safe et peuvent être utilisés simultanément à partir de plusieurs threads.