本文主要以一个简单的小例子,描述C# Winform程序异常关闭时,如何进行捕获,并记录日志。

概述

有时在界面的事件中,明明有try... catch 进行捕获异常,但是还是会有异常关闭的情况,所以在程序中如何最终的记录一些无法捕获的异常,会大大方便问题的定位分析及程序优化。

涉及知识点

以下两个异常事件,主要应用不同的场景。

  • Application.ThreadException 在发生应用程序UI主线程中未捕获线程异常时发生,触发的事件。
  • AppDomain.CurrentDomain.UnhandledException 当后台线程中某个异常未被捕获时触发。

主要源代码

主要程序(Program):

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace DemoException
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理非线程异常
AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException) ;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
glExitApp = true;//标志应用程序可以退出
} /// <summary>
/// 是否退出应用程序
/// </summary>
static bool glExitApp = false; /// <summary>
/// 处理未捕获异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{ SaveLog("-----------------------begin--------------------------");
SaveLog("CurrentDomain_UnhandledException"+DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
SaveLog("IsTerminating : " + e.IsTerminating.ToString());
SaveLog(e.ExceptionObject.ToString());
SaveLog("-----------------------end----------------------------");
while (true)
{//循环处理,否则应用程序将会退出
if (glExitApp)
{//标志应用程序可以退出,否则程序退出后,进程仍然在运行
SaveLog("ExitApp");
return;
}
System.Threading.Thread.Sleep( * );
};
} /// <summary>
/// 处理UI主线程异常
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
SaveLog("-----------------------begin--------------------------");
SaveLog("Application_ThreadException:" + e.Exception.Message);
SaveLog(e.Exception.StackTrace);
SaveLog("-----------------------end----------------------------");
} public static void SaveLog(string log)
{
string filePath =AppDomain.CurrentDomain.BaseDirectory+ @"\objPerson.txt";
//采用using关键字,会自动释放
using (FileStream fs = new FileStream(filePath, FileMode.Append))
{
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.WriteLine(log);
}
}
}
}
}

出错的程序:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace DemoException
{
public partial class FrmMain : Form
{ public FrmMain()
{
InitializeComponent();
} private void FrmMain_Load(object sender, EventArgs e)
{ } private void btnTestUI_Click(object sender, EventArgs e)
{
int a = ;
int c = / a;
} private void btnTest2_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(() =>
{
int a = ;
int c = / a;
}));
t.IsBackground = true;
t.Start();
}
}
}

下载链接

C# 程序异常关闭时的捕获的更多相关文章

  1. [QT]问题记录-控件初始化导致程序异常关闭

    qt新手,在设置 pushButton 的字体颜色时,出现软件异常闭,代码如下: 按钮的初始化在  ui->setupUi(this); 前边,会出现一下问题. 解决办法:将按钮的初始化在  u ...

  2. 程序异常捕获库 - CrashRpt

    CrashRpt.dll用来在应用程序出现异常crash时,捕获到错误. 并收集出错信息: MiniDump文件.硬件信息.系统信息.出错信息.进程信息.服务信息.驱动信息.启动信息.软件列表.端口信 ...

  3. TCP异常关闭研究分析

    版权声明:本文由谢代斌原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/108 来源:腾云阁 https://www.qclo ...

  4. Java异常关闭资源的两种方式

    try-catch-finally 常用,在异常关闭时应判断流是否为空 public class CloseableUtils { public static void closeable(Close ...

  5. Runtime.getRuntime().addShutdownHook(Thread thread) 程序关闭时钩子,优雅退出程序

    根据 Java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象.在Runtime 注册后,如果JVM要停止前,这些 shutdown hook 便开始执行.也就是在 ...

  6. qt 单文档程序关闭时在delete ui处出现segmentation fault

    做了个显示图片的单文档程序. qt 单文档程序关闭时在delete ui处出现segmentation fault. 调试发现调用两次mainwindow析构函数. http://blog.csdn. ...

  7. android捕获程序异常退出

    今天看到迅雷动漫里面一个CrashHandler 的类,我猜是崩溃处理类.进去一看.果然.顺便学习一下. Android系统的"程序异常退出",给应用的用户体验造成不良影响.为了捕 ...

  8. C#WinForm程序异常退出的捕获、继续执行与自动重启

    本文参考网上搜索的信息,并做了适当修改可以让捕捉到异常之后阻止程序退出. 另给出了通过命令行自动重启的方法. 如果一个线程里运行下面的代码 ; / a; 将会导致程序自动结束,而且没有任何提示信息 但 ...

  9. java 检查抛出的异常是否是要捕获的检查性异常或运行时异常或错误

    /** * Return whether the given throwable is a checked exception: * that is, neither a RuntimeExcepti ...

随机推荐

  1. 源码安装python +NGINX 的坎坷路 +uwsgi安装 部署django 的CRM项目

    一.Nginx安装(基于ubuntu17.10 版本) 首先我们是基于源码安装,主要有如下步骤 1.安装依赖包 1.安装gcc g++的依赖库 sudo apt-get install build-e ...

  2. Python基础之面向对象思维解决游戏《天龙八部》

    一.程序设计思维: 以面向对象的思维设计<天龙八部>游戏技能,使得技能效果在增加或者减少时,游戏技能整体框架不改变,仅仅增加或者减少技能效果 二.思路流程图如下: 三.变成框架实现代码: ...

  3. TCPDF 背景图片透明度

    1.TCPDF 背景图片透明度  参考:https://bbs.csdn.net/topics/392364981 效果: 2.画一条线: 2.1方法解说  /*画一条线: x1:线条起点x坐标 y1 ...

  4. Samba部署共享服务

    在本地PC文件共享 Samba服务程序是一款基于SMB协议并由服务端和客户端组成的开源文件共享资源软件,实现了Windows和Linux系统间的文件共享 1.安装Samba服务程序    yum in ...

  5. CABaRet: Leveraging Recommendation Systems for Mobile Edge Caching

    CABaRet:利用推荐系统进行移动边缘缓存 本文为SIGCOMM 2018 Workshop (Mobile Edge Communications, MECOMM)论文. 笔者翻译了该论文.由于时 ...

  6. Python课程学习总结

    Python的介绍 Python是一种高级动态.完全面向对象的语言,函数.模块.数字.字符串都是对象,并且完全支持继承.重载.派生.多继承,有益于增强源代码的复用性. Python是一种计算机程序设计 ...

  7. [Swift]LeetCode55. 跳跃游戏 | Jump Game

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  8. [Swift]LeetCode295. 数据流的中位数 | Find Median from Data Stream

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

  9. [Swift]LeetCode318. 最大单词长度乘积 | Maximum Product of Word Lengths

    Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the tw ...

  10. [Swift]LeetCode892. 三维形体的表面积 | Surface Area of 3D Shapes

    On a N * N grid, we place some 1 * 1 * 1 cubes. Each value v = grid[i][j] represents a tower of v cu ...