C# 为什么不是';难道这不是最后被处死吗?
我的假设是,只要程序在运行,finally块就会一直被执行。然而,在这个控制台应用程序中,finally块似乎没有被执行C# 为什么不是';难道这不是最后被处死吗?,c#,.net,exception,try-catch,try-finally,C#,.net,Exception,Try Catch,Try Finally,我的假设是,只要程序在运行,finally块就会一直被执行。然而,在这个控制台应用程序中,finally块似乎没有被执行 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static v
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
}
}
}
}
输出
注意:当抛出异常时,windows询问我是否要结束应用程序,我说“是”。它实际执行。只是你没有注意到。当您看到
Windows正在检查问题的解决方案时
单击“取消”并查看它
您可能正在调试,当您单击“否”时,调试器将暂停执行。从命令行运行时。当Windows试图优雅地结束应用程序时,如果应用程序没有响应,请单击
no
或cancel
。
异常会在堆栈中冒泡,直到找到处理程序。否则,程序将退出。在你的场景中就是这样。。。没有处理程序,因此程序在到达finally块之前退出。当“ConsoleApplication1”停止响应时,您有两个选择 如果按“取消”,则允许未处理的异常继续,直到应用程序最终终止。这允许执行
finally
块。如果不按“取消”,则会停止进程,收集小型转储,然后终止应用程序。这意味着不会执行finally
块
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
}
}
}
}
或者,如果用更高的方法处理异常,您肯定会看到finally
块。例如:
static void unhandled()
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
}
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
try
{
unhandled();
}
catch ( Exception )
{
// squash it
}
}
始终“最终”给出输出单击
no
并查看发生了什么从命令行而不是在您的IDE中运行它看起来很奇怪。”“finally”应该在StackTrace之后写入。没有捕获,异常未处理,应用程序quitsIlya-没有选择点击“否”。另一个选项是“调试”。Kevin-它是从命令行运行的,而不是IDE。您在什么环境中运行?我使用的是Windows7,64。当它询问您“Windows正在检查问题的解决方案…”时,不要单击“取消”。让它做它自己的事情。-1–finally
应该在堆栈冒泡之前执行–事实上,在堆栈展开期间。如果没有捕获,finally的整个用途显然就失去了作用?这对我来说是一个新问题:对不起,这是一个轻率的回答。你在什么环境下跑步?我使用的是Windows7,64。当它询问您“Windows正在检查问题的解决方案…”时,不要单击“取消”。让它做自己的事情。然后Windows将终止应用程序,而不让它打印到控制台