C#中的未处理异常的拦截

C#中的未处理异常的拦截

直接挂接
Application.ThreadException
(仅限WinForms,且只对UI线程有效)
或者
AppDomain.CurrentDomain.UnhandledException
事件

一般采用ThreadException方法,AppDomain的那个操作起来比较麻烦,因为同时受.net和操作系统监控,可能最终效果不理想。

另外,不要两个同时使用,只有一个会工作。

这两种处理方法都是在各自领域内工作的,ThreadException会捕获UI线程上的未处理异常,AppDomain.UnhandledException在域内有效
也就是说,后者要比前者低级一些,毕竟WinForms要跑在一个域内

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace SetUnhandledExceptionFilter
{
    public partial class Form1 : Form
    {
        public delegate Int32 CallBack(ref long a);
        CallBack mycall;
        [DllImport("kernel32")]
        private static extern void RtlMoveMemory(ref byte dst,
        ref byte src, Int32 len);
        [DllImport("kernel32")]
        private static extern Int32 SetUnhandledExceptionFilter(CallBack cb);
        public static Int32 newexceptionfilter(ref long a)
        {

            MessageBox.Show("截获了全局异常!");
            return 0;
        }

        public Form1()
        {
            InitializeComponent();

            mycall = new CallBack(newexceptionfilter);
            SetUnhandledExceptionFilter(mycall);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte a = 1, b = 2;
            MessageBox.Show("a=" + a.ToString());
            RtlMoveMemory(ref a, ref b, 200);
            MessageBox.Show("a=" + a.ToString());
        }

    }
}

但是运行后并没起到截获异常的效果:
按预想效果,点击 button1 后,应该弹出一个截获了全局异常!”这样的对话框。

实际情况是:
当代码RtlMoveMemory(ref a, ref b, int c)c=200时,程序报错“SetUnhandledExceptionFilter .vshost.exe[2504]中发生未处理的win32异常。
c=2000时,程序直接退出,没有任何显示(没有预想的截获了全局异常!”),请问这是什么原因呢?

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值