在以下程序中,如何将OverflowException传播到Main?
class Program
{
static readonly CancellationTokenSource Source = new CancellationTokenSource();
static void Main(string[] args)
{
CallDoSomething(1);
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
static void CallDoSomething(int foo)
{
var task = Task.Factory.StartNew(() => DoSomething(foo), Source.Token);
task.ContinueWith(t =>
{
var result = task.Result;
Console.WriteLine(result);
Thread.Sleep(500);
CallDoSomething(result);
}, TaskContinuationOptions.NotOnCanceled);
task.ContinueWith(t => t.Exception?.Handle(ex => throw ex), TaskContinuationOptions.OnlyOnFaulted);
}
static int DoSomething(int foo)
{
if (foo > 100)
{
Source.Cancel();
throw new OverflowException("foo overflowed");
}
return foo * 2;
}
}