gpt4 book ai didi

C# – try{}catch(Exception ex){} – 不捕获任何异常

转载 作者:太空宇宙 更新时间:2023-11-03 12:25:42 25 4
gpt4 key购买 nike

<分区>

简短版,这个方法:

public override async void MethodWithException()
{
throw new Exception("any EXCEPTION type and format will be skipped by outer try-catch block");
}

没有被这个 block 捕获(“捕获”被跳过):

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 block 像往常一样再次工作有任何建议,请告诉我。谢谢!这是第一次,当 catch block 有如此奇怪的行为时。

下载:console application demo project – https://www.dropbox.com/s/x8ta7dndbijxbvq/ConsoleAppExceptionTryCatchProblem.zip?dl=1 (请不要调试运行,以便您可以立即看到结果)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com