简体   繁体   中英

Exception handling in tasks in c#

I have problems with exception handling in tasks. I've found on MSDN the page to exception handling in tasks, but the example doesn't work for me...

I would expect, that the exception should be handled, but if I start the program, I get an unhandled exception error.

Thanks.

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

}

Returning false is rethrowing the Exception. If you just want to print the extra error information, then replace the return false with return true and get rid of the return in the if block.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM