c#中任务中的异常处理

时间:2015-03-11 13:23:14

标签: c# exception-handling task

我在任务中遇到异常处理问题。我在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();
    }
}

}

1 个答案:

答案 0 :(得分:2)

返回false正在重新抛出异常。如果您只想打印额外的错误信息,请将return false替换为return true并删除return块中的if

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; 
        });