AggregateException Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Representa um ou mais erros que ocorrem durante a execução da aplicação.
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
- Herança
- Atributos
Exemplos
O exemplo seguinte apanha a AggregateException exceção e chama o Handle método para tratar cada exceção que contém. Compilar e executar o exemplo com a primeira task1 variável deve resultar num AggregateException objeto que contenha uma UnauthorizedAccessException exceção. Comentar essa linha, descomentar a segunda task1 variável e compilar e executar o exemplo produz um AggregateException objeto que contém uma IndexOutOfRangeException exceção.
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
Observações
AggregateException é usado para consolidar múltiplas falhas num único objeto excecional projetável. É amplamente utilizado na Task Parallel Library (TPL) e no Parallel LINQ (PLINQ). Para obter mais informações, consulte Tratamento de exceções e Como manipular exceções em uma consulta PLINQ. Para informações adicionais, consulte a entrada Agregando Exceções no blogue .NET Matters.
Construtores
| Name | Description |
|---|---|
| AggregateException() |
Inicializa uma nova instância da AggregateException classe com uma mensagem fornecida pelo sistema que descreve o erro. |
| AggregateException(Exception[]) |
Inicializa uma nova instância da AggregateException classe com referências às exceções internas que são a causa dessa exceção. |
| AggregateException(IEnumerable<Exception>) |
Inicializa uma nova instância da AggregateException classe com referências às exceções internas que são a causa dessa exceção. |
| AggregateException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da AggregateException classe com dados serializados. |
| AggregateException(String, Exception) |
Inicializa uma nova instância da AggregateException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
| AggregateException(String, Exception[]) |
Inicializa uma nova instância da AggregateException classe com uma mensagem de erro especificada e referências às exceções internas que são a causa dessa exceção. |
| AggregateException(String, IEnumerable<Exception>) |
Inicializa uma nova instância da AggregateException classe com uma mensagem de erro especificada e referências às exceções internas que são a causa dessa exceção. |
| AggregateException(String) |
Inicializa uma nova instância da AggregateException classe com uma mensagem especificada que descreve o erro. |
Propriedades
| Name | Description |
|---|---|
| Data |
Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção. (Herdado de Exception) |
| HelpLink |
Obtém ou define um link para o ficheiro de ajuda associado a esta exceção. (Herdado de Exception) |
| HResult |
Recebe ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
| InnerException |
Obtém a Exception instância que causou a exceção atual. (Herdado de Exception) |
| InnerExceptions |
Obtém uma coleção de apenas leitura das Exception instâncias que causaram a exceção atual. |
| Message |
Recebe uma mensagem que descreve a exceção. |
| Message |
Recebe uma mensagem que descreve a exceção atual. (Herdado de Exception) |
| Source |
Obtém ou define o nome do aplicativo ou o objeto que causa o erro. (Herdado de Exception) |
| StackTrace |
Obtém uma representação string dos frames imediatos na stack de chamadas. (Herdado de Exception) |
| TargetSite |
Obtém o método que lança a exceção atual. (Herdado de Exception) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| Flatten() |
Achata uma AggregateException instância numa única instância nova. |
| GetBaseException() |
Devolve o Exception que é a causa raiz desta exceção. Esta exceção é ou a exceção raiz ou a primeira AggregateException que contém múltiplas exceções internas ou nenhuma exceção interna. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da AggregateException classe com dados serializados. |
| GetType() |
Obtém o tipo de execução da instância atual. (Herdado de Exception) |
| Handle(Func<Exception,Boolean>) |
Invoca um manipulador em cada Exception um contido por este AggregateException. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Cria e devolve uma representação de cadeia da corrente AggregateException. |
evento
| Name | Description |
|---|---|
| SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção. (Herdado de Exception) |
Aplica-se a
Segurança de Thread
Todos os membros públicos e protegidos são AggregateException seguros para threads e podem ser usados simultaneamente a partir de múltiplos threads.