C#– try {} catch(异常例外){} –不捕获任何异常 [英] C# – try{}catch(Exception ex){} – do NOT caught any exception

查看:734
本文介绍了C#– try {} catch(异常例外){} –不捕获任何异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短版本,此方法:

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

没有被该代码块捕获( catch被跳过):

is not caught by this block ("catch" is skipped):

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

}





完整:请看一下我制作的简短演示:

This is super strange behaviour.

Full: please take a look at the short demo, that I made:

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....
    }
}

这是来自实际项目的简化示例。如果您有任何建议,如往常一样,如何使挡块再次工作,请告诉我。谢谢!
这是第一次,当捕获块具有如此奇怪的行为。

This is simplified example from real project. If you have any suggestion how to make catch block to work again, as usual, please let me know. Thanks! This is first time, when catch block have such a strange behaviour.

下载:控制台应用程序演示项目– https://www.dropbox.com/s/x8ta7dndbijxbvq/ConsoleAppExceptionTryCatchProblem.zip?dl=1 (请在没有调试的情况下运行,以便您可以立即看到结果)

Download: console application demo project – https://www.dropbox.com/s/x8ta7dndbijxbvq/ConsoleAppExceptionTryCatchProblem.zip?dl=1 (please run without a debugging, so that you can immediately see the result)

推荐答案

感谢所有人的回答,尤其是@MickyD与文章的很好链接

Thank everyone for the answers, especially @MickyD for great link with article

答案:避免异步无效说明-https://msdn.microsoft.com/zh-cn/magazine/jj991977.aspx

如果有人遇到同样的问题,请修复代码,并进行所有注释更改:

If anybody will have same problem, fixed code, all changes with comments:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("1. Program starts"); //+++ Yes, in the console
        RealClassFromAbstract realClassFromAbstractObject = new RealClassFromAbstract();


        Task.Factory.StartNew(async () =>//CHANGE 1/5: async lambda
        {
            try
            {
                //CHANGE 2/5: await
                await realClassFromAbstractObject.MethodWithException();


                Console.WriteLine("Nothing in the console, that's correct"); //--- Notihng in the console

            }
            catch (Exception exception)
            {
                Console.WriteLine("2. Nice, exception! " + exception); //+++ Yes, in the console!

            }
        }).ConfigureAwait(false);



        Console.WriteLine("3. Program ends"); //+++ Yes, in the console
        Console.ReadKey();
    }
}

abstract class AbstractClass
{
    //CHANGE 3/5: returned type is Task
    public abstract Task MethodWithException();
}

class RealClassFromAbstract : AbstractClass
{
    //CHANGE 4/5: returned type is Task according to the abstact class
    public override async Task MethodWithException()
    {
        throw new Exception("This exception would be caught by outer try-catch block");


        //Anythig else, await....
        await Task.Delay(3);


        //CHANGE 5/5: await or:
        return;//or "Task.CompletedTask" in .NET >=4.6 if no awaits or Task.FromResult() in .NET <4.6
    }
}

该项目的代码部分确实很旧。第一个版本是同步的->第二个版本是与BackgroundWorker一起使用的->在该直接线程之后,并且仅在-> – Task之后,但在异步/等待之前。
在最后阶段,开发过程中出错了。

In the real project, that part of the code, was really old. First version was synchronous -> second was working with together with BackgroundWorker -> after that straight Threads and only after ->– Task, but before async/await. At the last stage, errors were made during the development.

最有趣的是,一切正常运行了至少两年没有问题。仅在上周进行测试时,我才收到奇怪的应用程序级异常。
非常感谢您的所有回答!

Most interesting that everything was working for at least two years without problems. I got strange application level exceptions only last week while testing. Thanks you very much for all answers!

这篇关于C#– try {} catch(异常例外){} –不捕获任何异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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