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 ...
随机推荐
- 权限组件之rbac
rbac:基于角色的权限访问控制(Role-Based Access Control). rbac的主要流程:给每个角色赋予不同的权限,是这个角色的员工都有这个角色的所有权限.一个角色可以有多个人员担 ...
- 【ASP】response和sever对象实现用户登录
1.问题提出 设计两个登录界面:一个register.asp页面用于输入账号,密码等信息进行登录.另一个页面welcome.asp用于显示登录成功的信息.利用request的两个对象response和 ...
- pip和cmd常用命令
1.pip常用命令 显示模块的详情 pip show 安装模块 pip install 模块名称 卸载模块 pip uninstall 模块名称 查看当前环境 ...
- 关于使用jquery对input中type为radio的标签checked属性的增加与移除
需求:对radio的checked属性先消除然后进行重新设置: 初步方案: $("auForm input :radio[value='0']").removeAttr('chec ...
- IOS菜鸟学习
1.NS是系统库.2.IOS类的声明:@interface MyObject : NSObject { int memberVar1; // 实体变量 id memberVar2;} + ...
- HTML5 history.pushState()和history.replaceState()新增、修改历史记录用法介绍
抽空研究了下这两个新方法,确实可以解决很多问题 1.使用pushState()方法 可以控制浏览器自带的返回按钮: 有时候我们想让用户点击浏览器返回按钮时,不返回,或执行其他操作,这时,就用到hist ...
- [Swift]LeetCode190. 颠倒二进制位 | Reverse Bits
Reverse bits of a given 32 bits unsigned integer. Example 1: Input: 00000010100101000001111010011100 ...
- [Swift]LeetCode565. 数组嵌套 | Array Nesting
A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest ...
- [Swift]LeetCode844. 比较含退格的字符串 | Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors. # m ...
- [Swift]LeetCode1014. 最佳观光组合 | Best Sightseeing Pair
Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and t ...