I'm trying to catch an NullReferenceException which is going to be thrown by Task.Factory.StartNew method. I think it should be caught by 'try' statement with task.Wait() method. I also referred to Why is this exception not caught?, but have no idea. Would you share your wisdom?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Csharp_study
{
class Program
{
static void Main(string[] args)
{
Task my_task = Task.Factory.StartNew(() => { throw null; });
try
{
my_task.Wait();
}
catch (AggregateException exc)
{
exc.Handle((x) =>
{
Console.WriteLine(exc.InnerException.Message);
return true;
});
}
Console.ReadLine();
}
}
}
This behavior is due to VS's debugger and not your code.
If you're in debug mode and have Just My Code enabled (which is the default setting for most languages), turning it off should do the trick.
To disable the Just My Code feature, go to Tools > Options > Debugging > General and uncheck Just My Code checkbox.
If you're wondering what enabling Just My Code feature does, here's a excerpt from msdn.
Enable Just My Code
When this feature is enabled, the debugger displays and steps into user code ("My Code") only, ignoring system code and other code that is optimized or that does not have debugging symbols.