C#捕捉全局异常

1.运行图片

2.源码

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 捕捉全局异常
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {

            //设置捕捉全局异常的程序
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;



            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //处理应用程序域中的异常
            Exception ex = e.ExceptionObject as Exception;
            if (ex != null)
            {
                MessageBox.Show($"发生了未处理的异常:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show($"发生了未处理的非托管异常", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            //处理线程异常
            MessageBox.Show($"发生了未处理的异常:{e.Exception.Message}\r\n" + $"错误的位置:{e.Exception.StackTrace}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

3,使用方法---->不用弹窗的方式,可以用写Log的方式写出来。

相关推荐
应用市场1 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
Dfreedom.2 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生2 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
虚行2 小时前
C#上位机工程师技能清单文档
开发语言·c#
小羊在睡觉3 小时前
golang定时器
开发语言·后端·golang
CoderCodingNo3 小时前
【GESP】C++四级真题 luogu-B4068 [GESP202412 四级] Recamán
开发语言·c++·算法
Larry_Yanan3 小时前
QML学习笔记(四十四)QML与C++交互:对QML对象设置objectName
开发语言·c++·笔记·qt·学习·ui·交互
百锦再4 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven
Want5954 小时前
C/C++大雪纷飞①
c语言·开发语言·c++
有时间要学习5 小时前
Qt——窗口
开发语言·qt