C# 应用异常捕获

program.cs

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationException.Run(call); // 调用异常信息捕获类,进行异常信息的捕获
}

// 应用程序,入口逻辑
public static void call()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

LogFile.instance.Start();
string Msg = string.Format("程序开始启动!!!");
LogFile.instance.LogInfo(Msg);
Application.Run(new FormMain());
}
}

ApplicationException.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Degassing
{
/// <summary>
/// 此类用于捕获Application异常信息
/// </summary>
class ApplicationException
{
/// <summary>
/// 定义委托接口处理函数,调用此类中的Main函数为应用添加异常信息捕获
/// </summary>
public delegate void ExceptionCall();

public static void Run(ExceptionCall exCall)
{
try
{
//设置应用程序处理异常方式:ThreadException处理
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

if (exCall != null) exCall();
}
catch (Exception ex)
{
string str = GetExceptionMsg(ex, string.Empty);
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string str = GetExceptionMsg(e.Exception, e.ToString());
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}

/// <summary>
/// 生成自定义异常消息
/// </summary>
/// <param name="ex">异常对象</param>
/// <param name="backStr">备用异常消息:当ex为null时有效</param>
/// <returns>异常字符串文本</returns>
static string GetExceptionMsg(Exception ex, string backStr)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("****************************异常文本****************************");
sb.AppendLine("【出现时间】:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
if (ex != null)
{
sb.AppendLine("【异常类型】:" + ex.GetType().Name);
sb.AppendLine("【异常信息】:" + ex.Message);
sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
sb.AppendLine("【异常方法】:" + ex.TargetSite);
}
else
{
sb.AppendLine("【未处理异常】:" + backStr);
}
sb.AppendLine("***************************************************************");

string strMsg = sb.ToString();
WriteLog(strMsg);
return strMsg;
}

static void WriteLog(string msg)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Application.StartupPath + "/log/exception.txt", true))
{
file.WriteLine(msg);
}
}
}
}

时间: 2024-08-15 06:18:53

C# 应用异常捕获的相关文章

.NET 基础 一步步 一幕幕[数组、集合、异常捕获]

数组.集合.异常捕获 数组: 一次性存储多个相同类型的变量. 一维数组: 语法: 数组类型[] 数组名=new 数组类型[数组长度]; 声明数组的语法: A.数据类型 [] 数组名称= new 数据类型[2]{1,2}: B.数据类型 [] 数组名称 = new 数据类型[数组大小]; C. 数据类型 [] 数组名称 = {数据,数据,数据,数据}; ***数组的长度一旦固定了,就不能再被改变了 可以通过索引来访问数组中的元素: 数组名称[索引位置] 案例: 多维数组:多个线性数组的值 二维:i

异常捕获

异常捕获,在现在很多ide工具里都可以用快捷键很方便的添加上,防止用户看到自己看不懂的报错甚至莫名其妙崩溃,导致用户体验不好. 哪怕显示一个友好一些的崩溃提示,也比直接显示error:xxxx xxxxxxxxx要好得多. 当然最终的目的还是要给出对应的解决办法,让代码可以继续运行. 1 <?php 2 header("content-type:text/html; charset=utf-8"); 3 /** 4 * 包裹重量异常 5 */ 6 class HeavyParce

电脑小白学习软件开发-C#的选择语句、异常捕获,进攻程序员

写代码也要读书,爱全栈,更爱生活.每日更新原创IT编程技术及日常实用视频. 我们的目标是:玩得转服务器Web开发,搞得懂移动端,电脑客户端更是不在话下. 不得不说,C#这门语言是小编以为最好的语言.其优美的语法,最具人性化的新特性,以及无敌的开发工具令人陶醉.接触过不少语言,却一直回味写C#的那种状态. 本人认为目前C#是比较适合入门的语言,最为小白,热衷于电脑编程开发的人,可谓是一个大大的福利. 不管如何写过多少中语言教程,在写C#教程时却是如此的富含感情.为了完成我们的全栈梦,作为服务器端,

WebAPI 过滤器拦截处理以及异常捕获

对action进行拦截处理 public class UserAuthorizeAttribute : ActionFilterAttribute { /// <summary> /// CC调用的Token /// </summary> //private static readonly string CCToken = ConfigurationManager.AppSettings["CCToken"].ToString(); /// <summar

iphone 异常捕获处理

iphone 异常捕获处理 1 void UncaughtExceptionHandler(NSException *exception) { 2 NSArray *arr = [exception callStackSymbols]; 3 NSString *reason = [exception reason]; 4 NSString *name = [exception name]; 5 NSString *urlStr = [NSString stringWithFormat:@"mai

javascript异常捕获笔记

异常捕获 1.异常 当JavaScript引擎执行Javascript代码时,发生了错误,导致程序停止运行 2.异常抛出 当异常产生,并且将这个异常生成一个错误信息 3.异常捕获 try{ 发生异常的代码块: }catch(err){ 错误信息处理: } function demo(){ try{ alert(str); }catch(error){ console.log(error);//==>ReferenceError: str is not defined(-) } } demo();

JAVA并发,线程异常捕获

由于线程的特性,当我们启动了线程是没有办法用try catch捕获异常的,如下例: 1 package com.xt.thinks21_2; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 /** 7 * 线程异常捕获测试 8 * 9 * @author xue 10 * 11 */ 12 public class ThreadUncaughtExcepti

Spring-MVC开发之全局异常捕获全面解读(转)

异常,异常.我们一定要捕获一切该死的异常,宁可错杀一千也不能放过一个!产品上线后的异常更要命,一定要屏蔽错误内容,以免暴露敏感信息!在用Spring MVC开发WEB应用时捕获全局异常的方法基本有两种: WEB.XML,就是指定error-code和page到指定地址,这也是最传统和常见的做法 用Spring的全局异常捕获功能,这种相对可操作性更强一些,可根据自己的需要做一后善后处理,比如日志记录等. SO,本文列出Spring-MVC做WEB开发时常用全局异常捕获的几种解决方案抛砖引玉,互相没

Java异常捕获

1 public class Main { 2 3 /** 4 * 在写异常处理的时候,一定要把异常范围小的放在前面,范围大的放在后面, 5 * Exception这个异常的根类一定要刚在最后一个catch里面, 6 * 如果放在前面或者中间,任何异常都会和Exception匹配的,就会报已捕获到异常的错误. 7 * @param args 8 */ 9 public static void main(String[] args) { 10 int a[] = new int[] {1,2,3,

01.异常捕获

什么是异常? 解释:语法上没有错误,在程序运行的过程当中,犹豫某些原因,程序出现了错误,不能再正常运行. 我们在程序中经常会出现各种各样的异常,如果想要程序坚强一点, 我么应该经常性的的使用try-catch来进行异常捕获. 窍门: 哪行代码有可能出现异常,我们就try它一下 语法: try { 可能会出现异常的代码; } catch { 出现异常后要执行的代码; } 执行过程: 如果try中的的代码,没有出现异常,catch中的代码不会被执行. 如果try中的代码出现了异常,在出现异常的代码之