为什么这个异常没有抓到? [英] Why is this exception not caught?

查看:127
本文介绍了为什么这个异常没有抓到?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行下面的代码:

I'm trying to run the following code:

class Program
{
    static void Main(string[] args)
    {
        var task = Task.Factory.StartNew(() =>
            {
                throw new ApplicationException("message");
            });
        try
        {
            task.ContinueWith(t => Console.WriteLine("End"));
        }
        catch (AggregateException aex)
        {
            Console.Write(aex.InnerException.Message);
        }
    }
}



我预计例外将在以下位置被捕获:

I expected that the Exception would be caught in the following location:

        catch (AggregateException aex)
        {
            Console.Write(aex.InnerException.Message);
        }



但是,这不会发生。为什么会这样?

But this is not happening. Why is this so?

推荐答案

您是刚刚印刷出来的任务 - 。这甚至不会有尚未完成

You're just printing out the task - which won't even have completed yet.

打印出来的任务不会等待它完成,或者尝试获取值

Printing out the task doesn't wait for it to complete, or try to fetch the value.

如果你改变你的代码:

try
{
    task.Wait();
}



... 然后的我希望它为了捕获异常

... then I'd expect it to catch the exception.

(我以前使用任务< T>。结果,但我注意到,这是没有返回值的任务,所以它也只是非泛型工作

(I was previously using Task<T>.Result, but I notice this is a task with no return value, so it would just be the non-generic Task.)

这篇关于为什么这个异常没有抓到?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆