【发布时间】:2015-03-11 13:23:13
【问题描述】:
我在任务中遇到异常处理问题。我在 MSDN 上找到了任务中异常处理的页面,但是该示例对我不起作用...
我希望应该处理异常,但是如果我启动程序,我会收到未处理的异常错误。
谢谢。
https://msdn.microsoft.com/en-us/library/dd537614%28v=vs.110%29.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaskExceptionTest
{
class Program
{
static string[] GetAllFiles(string str)
{
// Should throw an AccessDenied exception on Vista.
return System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories);
}
static void HandleExceptions()
{
// Assume this is a user-entered string.
string path = @"C:\";
// 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
{
task1.Wait();
}
catch (AggregateException ae)
{
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 has completed.");
}
static void Main(string[] args)
{
HandleExceptions();
}
}
}
【问题讨论】:
-
“我收到一个未处理的异常错误。” - 有机会分享错误吗?
-
“未处理的异常错误” - 哪个异常?在哪一行?被抓到了吗?如果你按 F5 会发生什么?
-
UnauthorizedAccesException 在返回 System.IO.Directory.GetFiles(str, "*.txt", System.IO.SearchOption.AllDirectories); 时未被用户代码处理
-
您没有访问该目录的权限,这就是它首先被抛出的原因。
-
是的,但稍后将在 task.wait 中处理。它会在那里被捕获,但我已经在 GetAllFiles 中得到了未处理的异常。我应该怎么做才能没有任何未处理的异常?
标签: c# exception-handling task