尝试后终于不叫了 [英] finally not called after try

查看:142
本文介绍了尝试后终于不叫了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我无法在控制台应用程序中运行我的finally块.我正在编写此代码来测试finally块的工作原理,因此非常简单:

For some reason within my console application I cannot get my finally block to run. I was writing this code to test how the finally block works so it is very simple:

static void Main()
{
    int i = 0;
    try
    {
        int j = 1 / i; // Generate a divide by 0 exception.
    }
    finally
    {

        Console.Out.WriteLine("Finished");
        Console.In.ReadLine();
    }
}

起初,我有

At first I had the problem described here but then I tried to run the program outside Visual Studio I got a "Program has stopped responding" error.

推荐答案

想在这里添加我自己的发现,因为这里的行为肯定很奇怪-因此,接受的答案并不完全正确.

Wanted to add my own findings here as the behavior here is certainly strange - and as such, the accepted answer is not entirely correct.

给出以下示例:

static void Main(string[] args)
{
    try{
        throw new Exception("");
    } finally {
        Console.WriteLine("I am never called!");
        Console.ReadLine();
    }
}

如果我们选择从Windows错误报告对话框中取消,则finally块将实际执行,例如:

The finally block is actually executed IF we choose to CANCEL out of the Windows Error Reporting Dialog, as such:

但是,如果我们允许Windows错误报告对话框完成",那么我们可以选择调试"或关闭程序",则不会执行finally块.

HOWEVER, if we allow the Windows Error Reporting Dialog to "complete", so we get the option to "Debug" or "Close Program", then the finally block is NOT executed.

对我来说,这表明.NET运行时实际上将运行所有finally块,而不管是否遇到未处理的顶级异常",并且阻止这样做的实际上是Windows(如果选择关闭程序")或Visual Studio调试器(如果您选择调试"或正在连接调试器开始)...因为它们会在运行时之前杀死进程,从而有机会继续进行.

Which to me indicates that the .NET Runtime WILL actually run all finally blocks, regardless of experiencing a "Unhandled top level Exception", and that what's preventing it from doing so is actually Windows (if you select "Close Program") or the Visual Studio Debugger (if you select "Debug" or is starting with the debugger attached)... As they kill the process before the Runtime as a chance to proceed.

有什么想法吗?

这篇关于尝试后终于不叫了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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