C# 程序异常关闭时的捕获
本文主要以一个简单的小例子,描述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# 程序异常关闭时的捕获的更多相关文章
- [QT]问题记录-控件初始化导致程序异常关闭
qt新手,在设置 pushButton 的字体颜色时,出现软件异常闭,代码如下: 按钮的初始化在 ui->setupUi(this); 前边,会出现一下问题. 解决办法:将按钮的初始化在 u ...
- 程序异常捕获库 - CrashRpt
CrashRpt.dll用来在应用程序出现异常crash时,捕获到错误. 并收集出错信息: MiniDump文件.硬件信息.系统信息.出错信息.进程信息.服务信息.驱动信息.启动信息.软件列表.端口信 ...
- TCP异常关闭研究分析
版权声明:本文由谢代斌原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/108 来源:腾云阁 https://www.qclo ...
- Java异常关闭资源的两种方式
try-catch-finally 常用,在异常关闭时应判断流是否为空 public class CloseableUtils { public static void closeable(Close ...
- Runtime.getRuntime().addShutdownHook(Thread thread) 程序关闭时钩子,优雅退出程序
根据 Java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象.在Runtime 注册后,如果JVM要停止前,这些 shutdown hook 便开始执行.也就是在 ...
- qt 单文档程序关闭时在delete ui处出现segmentation fault
做了个显示图片的单文档程序. qt 单文档程序关闭时在delete ui处出现segmentation fault. 调试发现调用两次mainwindow析构函数. http://blog.csdn. ...
- android捕获程序异常退出
今天看到迅雷动漫里面一个CrashHandler 的类,我猜是崩溃处理类.进去一看.果然.顺便学习一下. Android系统的"程序异常退出",给应用的用户体验造成不良影响.为了捕 ...
- C#WinForm程序异常退出的捕获、继续执行与自动重启
本文参考网上搜索的信息,并做了适当修改可以让捕捉到异常之后阻止程序退出. 另给出了通过命令行自动重启的方法. 如果一个线程里运行下面的代码 ; / a; 将会导致程序自动结束,而且没有任何提示信息 但 ...
- java 检查抛出的异常是否是要捕获的检查性异常或运行时异常或错误
/** * Return whether the given throwable is a checked exception: * that is, neither a RuntimeExcepti ...
随机推荐
- Linux 搭建Nginx+uWSGI+Django环境
安装环境 sudo apt-get install nginx sudo apt install python3 sudo apt install python3-pip 使用 sudo pip3 i ...
- SharePoint 更改管理帐户密码步骤
// https://wenku.baidu.com/view/0fffab761ed9ad51f01df2df.html \
- python+SQLAlchemy+爬虫
python+SQLAlchemy+爬虫 前面分享了SQLAlchemy的知识,这次我共享一下学习用python开发爬虫再把爬出来的数据放到用SQLAlchemy的数据库上面的知识,当然我这个是带测试 ...
- VBS列出windows更新列表
Set objSession = CreateObject("Microsoft.Update.Session") Set objSearcher = objSession.Cre ...
- [Swift]LeetCode53. 最大子序和 | Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has ...
- [Swift]LeetCode674. 最长连续递增序列 | Longest Continuous Increasing Subsequence
Given an unsorted array of integers, find the length of longest continuous increasing subsequence (s ...
- [Swift]LeetCode920. 播放列表的数量 | Number of Music Playlists
Your music player contains N different songs and she wants to listen to L (not necessarily different ...
- [Swift]LeetCode928. 尽量减少恶意软件的传播 II | Minimize Malware Spread II
(This problem is the same as Minimize Malware Spread, with the differences bolded.) In a network of ...
- 在admui中怎样上传本地文件?
1.首先需要引入一些插件 css: <link rel="stylesheet" href="/vendor/blueimp-file-upload/jquery. ...
- 工作随笔—Java容器基础知识分享(持有对象)
1. 概述 通常,程序总是运行时才知道的根据某些条件去创建新对象.在此之前,不会知道所需对象的数量,甚至不知道确切的类型,为解决这个普遍的编程问题:需要在任意时刻和任意位置创建任意数量的对象,所以,就 ...