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的方式写出来。

相关推荐
tianyu23413 小时前
Java 正则表达式终极指南:从 Pattern 到 Matcher,从双重转义到性能优化,一篇全搞定
java·开发语言·正则表达式·group·find·pattern·matcher
caimouse14 小时前
ReactOS 窗口系统分析(23):键盘 — keyboard.c + kbdlayout.c
c语言·开发语言·计算机外设
Emily1568535987015 小时前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module
就叫_这个吧20 小时前
Java递归方法实现面包屑导航
java·开发语言
fīɡЙtīиɡ ℡20 小时前
AI 应用系统设计
java·开发语言·人工智能
csdn_aspnet21 小时前
C# 在逗号分割的字符串中判断是否包含指定字符
c#·正则·linq·string·regex·contains
今天AI了吗21 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·数据库·人工智能·python·sql·深度学习·机器学习
宝桥南山1 天前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
TELL5211 天前
selenium webdriver 第二次初始化的异常
开发语言·python
动词ing1 天前
【C语言】自定义函数+指针入门
c语言·开发语言·算法