AggregateException 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示应用程序执行期间发生的一个或多个错误。
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
- 继承
- 属性
示例
以下示例捕获 AggregateException 异常并调用 Handle 该方法来处理它所包含的每个异常。 编译并运行包含第一个task1AggregateException变量的示例应生成包含UnauthorizedAccessException异常的对象。 注释掉该行,取消注释第二 task1 个变量,并编译并运行该示例将生成一个 AggregateException 包含 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
注解
AggregateException 用于将多个故障合并到单个可引发的异常对象中。 它在 任务并行库(TPL) 和 并行 LINQ(PLINQ)中广泛使用。 有关详细信息,请参阅 异常处理 和 作方法:处理 PLINQ 查询中的异常。 有关详细信息,请参阅 .NET Matters 博客中的 Aggregating Exceptions 条目。
构造函数
| 名称 | 说明 |
|---|---|
| AggregateException() |
使用描述错误的系统提供的消息初始化 AggregateException 类的新实例。 |
| AggregateException(Exception[]) |
使用对此异常原因的内部异常的引用初始化类的新实例 AggregateException 。 |
| AggregateException(IEnumerable<Exception>) |
使用对此异常原因的内部异常的引用初始化类的新实例 AggregateException 。 |
| AggregateException(SerializationInfo, StreamingContext) |
已过时.
使用序列化的数据初始化 AggregateException 类的新实例。 |
| AggregateException(String, Exception) |
使用指定的错误消息和对作为此异常原因的内部异常的引用初始化 AggregateException 类的新实例。 |
| AggregateException(String, Exception[]) |
使用指定的错误消息初始化类的新实例 AggregateException ,并引用作为此异常原因的内部异常。 |
| AggregateException(String, IEnumerable<Exception>) |
使用指定的错误消息初始化类的新实例 AggregateException ,并引用作为此异常原因的内部异常。 |
| AggregateException(String) |
使用描述错误的指定消息初始化 AggregateException 类的新实例。 |
属性
| 名称 | 说明 |
|---|---|
| Data |
获取键/值对的集合,这些键/值对提供有关异常的其他用户定义的信息。 (继承自 Exception) |
| HelpLink |
获取或设置与此异常关联的帮助文件的链接。 (继承自 Exception) |
| HResult |
获取或设置 HRESULT,它是分配给特定异常的编码数值。 (继承自 Exception) |
| InnerException |
Exception获取导致当前异常的实例。 (继承自 Exception) |
| InnerExceptions |
获取导致当前异常的实例的 Exception 只读集合。 |
| Message |
获取描述异常的消息。 |
| Message |
获取描述当前异常的消息。 (继承自 Exception) |
| Source |
获取或设置导致错误的应用程序或对象的名称。 (继承自 Exception) |
| StackTrace |
获取调用堆栈上即时帧的字符串表示形式。 (继承自 Exception) |
| TargetSite |
获取引发当前异常的方法。 (继承自 Exception) |
方法
| 名称 | 说明 |
|---|---|
| Equals(Object) |
确定指定对象是否等于当前对象。 (继承自 Object) |
| Flatten() |
将 AggregateException 实例平展为单个新实例。 |
| GetBaseException() |
返回 Exception 此异常的根本原因。 此异常是根异常或第一个包含多个内部异常或根本不包含内部异常的第一 AggregateException 个异常。 |
| GetHashCode() |
用作默认哈希函数。 (继承自 Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
已过时.
使用序列化的数据初始化 AggregateException 类的新实例。 |
| GetType() |
获取当前实例的运行时类型。 (继承自 Exception) |
| Handle(Func<Exception,Boolean>) |
对包含的每个 Exception 处理程序调用此 AggregateException处理程序。 |
| MemberwiseClone() |
创建当前 Object的浅表副本。 (继承自 Object) |
| ToString() |
创建并返回当前 AggregateException字符串表示形式。 |
活动
| 名称 | 说明 |
|---|---|
| SerializeObjectState |
已过时.
序列化异常以创建包含有关异常的序列化数据的异常状态对象时发生。 (继承自 Exception) |
适用于
线程安全性
所有公共成员和受保护的成员 AggregateException 都是线程安全的,并且可以同时从多个线程使用。