【发布时间】:2023-03-29 16:00:01
【问题描述】:
短版,这个方法:
public override async void MethodWithException()
{
throw new Exception("any EXCEPTION type and format will be skipped by outer try-catch block");
}
未被此块捕获(“catch”被跳过):
try
{
realClassFromAbstractObject.MethodWithException();
Console.WriteLine("Output in the console – NOT POSSIBLE but true!");
}
catch (Exception exception)
{
//Nothing caught!
Console.WriteLine("2. Nothing in console, skipped exception! " + exception); //--- Notihng in the output
}
这是非常奇怪的行为。
完整版:请看一下我制作的简短演示:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("1. Program starts"); //+++ Yes, in the console
RealClassFromAbstract realClassFromAbstractObject = new RealClassFromAbstract();
Task.Factory.StartNew(() =>
{
try
{
//Next method should to throw an exception! But nothing!
realClassFromAbstractObject.MethodWithException();
Console.WriteLine("In the console too – NOT POSSIBLE but true!"); //+++ Yes, in the console
}
catch (Exception exception)
{
//Nothing caught!
Console.WriteLine("2. Nothing in console, skipped exception! " + exception); //--- Notihng in the output
}
}).ConfigureAwait(false);
Console.WriteLine("3. Program ends"); //+++ Yes, in the console
Console.ReadKey();
}
}
abstract class AbstractClass
{
public abstract void MethodWithException();
}
class RealClassFromAbstract : AbstractClass
{
public override async void MethodWithException()
{
throw new Exception("any EXCEPTION type and format will be skipped by outer try-catch block");
throw new ArgumentException();
throw new DivideByZeroException();
//Anythig else, await....
}
}
这是来自真实项目的简化示例。如果您对如何使 catch 块像往常一样再次工作有任何建议,请告诉我。谢谢! 这是第一次,catch 块有这种奇怪的行为。
下载:console application demo project – https://www.dropbox.com/s/x8ta7dndbijxbvq/ConsoleAppExceptionTryCatchProblem.zip?dl=1(请不要调试运行,以便立即看到结果)
【问题讨论】:
-
我的精神力量告诉我,您需要在拨打
realClassFromAbstractObject.MethodWithException()之前输入await。 -
@RadosławCybulski 这是我的第一个猜测,但不幸的是,这并没有帮助,错误列表中有两个错误:“'await' 运算符只能在异步 lambda 表达式中使用。考虑标记这个带有 'async' 修饰符的 lambda 表达式。”和“不能等待'void'”。
-
使你的类异步或使用返回任务中的
.Result。 -
无法
catchasync voids 在Async/Await - Best Practices in Asynchronous Programming 有详细记录。我引用 "Exceptions from an Async Void Method Can’t Be Caught with Catch"