加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么最终没有被执行?

发布时间:2020-12-15 04:07:55 所属栏目:百科 来源:网络整理
导读:我的假设是,只要程序正在运行,finally块就会被执行.但是,在此控制台应用程序中,finally块似乎没有被执行. using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 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");
            }
        }
    }
}

产量

注意:当抛出异常时,Windows询问我是否要结束应用,我说’是’.

解决方法

当您获得“ConsoleApplication1”已停止响应时,您有两个选择.

如果按取消,则允许继续处理未处理的异常,直到最终终止应用程序.这允许finally块执行.如果您没有按取消,则Windows Error Reporting 暂停该过程,收集一个小型转储器,然后终止该应用程序.这意味着不执行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
    }
}

总是给出“最后”的输出

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读