AggregateException Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Rappresenta uno o più errori che si verificano durante l'esecuzione dell'applicazione.
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
- Ereditarietà
- Attributi
Esempio
Nell'esempio seguente viene rilevata l'eccezione AggregateException e viene chiamato il Handle metodo per gestire ogni eccezione contenuta. La compilazione e l'esecuzione dell'esempio con la prima task1 variabile devono comportare un AggregateException oggetto contenente un'eccezione UnauthorizedAccessException . Commentando la riga, rimuovere il commento dalla seconda task1 variabile e compilare ed eseguire l'esempio genera un AggregateException oggetto che contiene un'eccezione 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)
{
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
Commenti
AggregateException viene usato per consolidare più errori in un singolo oggetto eccezione generabile. Viene usata ampiamente in Task Parallel Library (TPL) e PARALLEL LINQ (PLINQ). Per altre informazioni, vedere Gestione delle eccezioni e Procedura: Gestire le eccezioni in una query PLINQ. Per altre informazioni, vedere la voce Aggregating Exceptions nel blog .NET Matters.
Costruttori
| Nome | Descrizione |
|---|---|
| AggregateException() |
Inizializza una nuova istanza della classe AggregateException con un messaggio fornito dal sistema che descrive l'errore. |
| AggregateException(Exception[]) |
Inizializza una nuova istanza della AggregateException classe con riferimenti alle eccezioni interne che sono la causa di questa eccezione. |
| AggregateException(IEnumerable<Exception>) |
Inizializza una nuova istanza della AggregateException classe con riferimenti alle eccezioni interne che sono la causa di questa eccezione. |
| AggregateException(SerializationInfo, StreamingContext) |
Obsoleti.
Inizializza una nuova istanza della classe AggregateException con dati serializzati. |
| AggregateException(String, Exception) |
Inizializza una nuova istanza della classe AggregateException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa di questa eccezione. |
| AggregateException(String, Exception[]) |
Inizializza una nuova istanza della AggregateException classe con un messaggio di errore specificato e fa riferimento alle eccezioni interne che sono la causa di questa eccezione. |
| AggregateException(String, IEnumerable<Exception>) |
Inizializza una nuova istanza della AggregateException classe con un messaggio di errore specificato e fa riferimento alle eccezioni interne che sono la causa di questa eccezione. |
| AggregateException(String) |
Inizializza una nuova istanza della classe AggregateException con un messaggio specificato che descrive l'errore. |
Proprietà
| Nome | Descrizione |
|---|---|
| Data |
Ottiene una raccolta di coppie chiave/valore che forniscono informazioni aggiuntive definite dall'utente sull'eccezione. (Ereditato da Exception) |
| HelpLink |
Ottiene o imposta un collegamento al file della Guida associato a questa eccezione. (Ereditato da Exception) |
| HResult |
Ottiene o imposta HRESULT, valore numerico codificato assegnato a un'eccezione specifica. (Ereditato da Exception) |
| InnerException |
Ottiene l'istanza Exception che ha causato l'eccezione corrente. (Ereditato da Exception) |
| InnerExceptions |
Ottiene una raccolta di sola lettura delle Exception istanze che hanno causato l'eccezione corrente. |
| Message |
Ottiene un messaggio che descrive l'eccezione. |
| Message |
Ottiene un messaggio che descrive l'eccezione corrente. (Ereditato da Exception) |
| Source |
Ottiene o imposta il nome dell'applicazione o dell'oggetto che causa l'errore. (Ereditato da Exception) |
| StackTrace |
Ottiene una rappresentazione di stringa dei fotogrammi immediati nello stack di chiamate. (Ereditato da Exception) |
| TargetSite |
Ottiene il metodo che genera l'eccezione corrente. (Ereditato da Exception) |
Metodi
| Nome | Descrizione |
|---|---|
| Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object) |
| Flatten() |
Rende flat un'istanza AggregateException di in un'unica istanza nuova. |
| GetBaseException() |
Restituisce l'oggetto Exception che rappresenta la causa radice di questa eccezione. Questa eccezione è l'eccezione radice o la prima AggregateException che contiene più eccezioni interne o nessuna eccezione interna. |
| GetHashCode() |
Funge da funzione hash predefinita. (Ereditato da Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Obsoleti.
Inizializza una nuova istanza della classe AggregateException con dati serializzati. |
| GetType() |
Ottiene il tipo di runtime dell'istanza corrente. (Ereditato da Exception) |
| Handle(Func<Exception,Boolean>) |
Richiama un gestore in ogni Exception oggetto contenuto in questo AggregateExceptionoggetto . |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| ToString() |
Crea e restituisce una rappresentazione di stringa dell'oggetto corrente AggregateException. |
Eventi
| Nome | Descrizione |
|---|---|
| SerializeObjectState |
Obsoleti.
Si verifica quando viene serializzata un'eccezione per creare un oggetto stato dell'eccezione contenente dati serializzati sull'eccezione. (Ereditato da Exception) |
Si applica a
Thread safety
Tutti i membri pubblici e protetti di AggregateException sono thread-safe e possono essere usati simultaneamente da più thread.