9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

タスクでの例外の取り扱いについて

Last updated at Posted at 2014-11-29

タスク内で発生した例外は、Wait()またはResult呼び出し時に放出される。例外はAggregateExceptionに集約されて、それがスローされる。

コード例1

public class ThrowErrorSample
{
    public static void Run() 
    {
        var task = Task.Factory.StartNew(() =>
        {
            Thread.Sleep(500);
            throw new Exception("なんらかのエラー");
        });

        try
        {
            task.Wait();
        }
        catch (AggregateException exc)
        {
            foreach (var innnerExc in exc.InnerExceptions)
            {
                Console.WriteLine("エラー:" + innnerExc.Message);
            }
        }
    }
}

コード例2 (await使用)

class Program
{
    static void Main(string[] args)
    {
        ThrowErrorSample2.Run();
        Console.ReadLine();
    }
}

public class ThrowErrorSample2
{
    public static async void Run()
    {
        var task = Task.Factory.StartNew(() =>
        {
            Thread.Sleep(500);
            throw new Exception("なんらかのエラー");
        });

        try
        {
            await task;
        }
        catch(Exception e)
        {
            //発生したException自体がスローされてくる
            Console.WriteLine("エラー:" + e.Message);
        }
    }
}
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?