C# 运行异常捕获

调用示例:

// 示例:Program.cs
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args = null)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            SciTools.RunningExceptionTool.Run(call);                     // 捕获运行异常
            //SciTools.RunningExceptionTool.Run(call, SendErrors);       // 捕获运行异常,并发送异常信息
            //SciTools.RunningExceptionTool.Run(call, SendErrors, args); // 捕获运行异常,并发送异常信息, Main方法有参数
        }

        /// <summary>
        /// 应用程序,入口逻辑
        /// </summary>
        public static void call(string[] args = null)
        {
            Application.Run(new Form1());
        }

        /// <summary>
        // 自定义异常信息处理逻辑
        /// </summary>
        public static void SendErrors(string errorMsg)
        {
            // 自定义异常信息处理逻辑
        }
    }

异常捕获类:

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

namespace SciTools
{
     示例:Program.cs
    //static class Program
    //{
    //    /// <summary>
    //    /// 应用程序的主入口点。
    //    /// </summary>
    //    [STAThread]
    //    static void Main(string[] args = null)
    //    {
    //        Application.EnableVisualStyles();
    //        Application.SetCompatibleTextRenderingDefault(false);

    //        SciTools.RunningExceptionTool.Run(call);                     // 捕获运行异常
    //        //SciTools.RunningExceptionTool.Run(call, SendErrors);       // 捕获运行异常,并发送异常信息
    //        //SciTools.RunningExceptionTool.Run(call, SendErrors, args); // 捕获运行异常,并发送异常信息, Main方法有参数
    //    }

    //    /// <summary>
    //    /// 应用程序,入口逻辑
    //    /// </summary>
    //    public static void call(string[] args = null)
    //    {
    //        Application.Run(new Form1());
    //    }

    //    /// <summary>
    //    // 自定义异常信息处理逻辑
    //    /// </summary>
    //    public static void SendErrors(string errorMsg)
    //    {
    //        // 自定义异常信息处理逻辑
    //    }
    //}

    /// <summary>
    /// 捕获运行时异常信息
    /// </summary>
    public class RunningExceptionTool
    {
        /// <summary>
        /// 定义委托接口处理函数,调用此类中的Main函数为应用添加异常信息捕获
        /// </summary>
        public delegate void MainFunction(string[] args = null);

        /// <summary>
        /// 异常信息回调处理逻辑
        /// </summary>
        public delegate void ExceptionMsg(string msg);
        private static ExceptionMsg Excall = null;
        public static bool showMessageBox = true;


        public static void Run(MainFunction main, ExceptionMsg ExCall = null, string[] args = null)
        {
            try
            {
                if (ExCall != null) RunningExceptionTool.Excall = ExCall;

                // 捕获
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(CatchThreadException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CatchUnhandledException);

                if (main != null)
                {
                    if (args == null) main();
                    else main(args);
                }
            }
            catch (Exception ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                if(showMessageBox) MessageBox.Show(str, "运行异常", MessageBoxButtons.OK, MessageBoxIcon.Error);

                //bool ok = (MessageBox.Show(str, "运行异常,提交bug信息?", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK);
                //if (ok) sendBugToAuthor(str);

                if (Excall != null) Excall(str);
            }
        }

        /// <summary>
        /// 捕获线程异常
        /// </summary>
        static void CatchThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            if (showMessageBox) MessageBox.Show(str, "运行异常", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (Excall != null) Excall(str);
        }

        /// <summary>
        /// 捕获未处理异常
        /// </summary>
        static void CatchUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            if (showMessageBox) MessageBox.Show(str, "运行异常", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (Excall != null) Excall(str);
        }

        /// <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("***************************************************************");

            return sb.ToString();
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,错误处理和异常处理是非常重要的,可以帮助我们优雅地处理运行时错误,并保护应用程序免受崩溃和不可预测的行为。以下是一些常见的C#错误处理和异常处理的技术和原则: 1. 异常(Exceptions):C#使用异常机制来处理运行时错误。当发生异常时,可以抛出(throw)异常,并使用try-catch语句来捕获(catch)和处理异常。 ```csharp try { // 可能会引发异常的代码 } catch (Exception ex) { // 处理异常的代码 } ``` 2. 异常类型(Exception Types):C#提供了许多内置的异常类型,例如`ArgumentException`、`InvalidOperationException`等。可以根据具体的情况选择合适的异常类型,或自定义异常类型。 ```csharp try { // 可能会引发异常的代码 } catch (ArgumentException ex) { // 处理特定类型的异常 } catch (Exception ex) { // 处理其他类型的异常 } ``` 3. finally块:除了try和catch块外,还可以使用finally块来确保无论是否发生异常,都会执行特定的代码。 ```csharp try { // 可能会引发异常的代码 } catch (Exception ex) { // 处理异常的代码 } finally { // 执行清理或资源释放的代码 } ``` 4. 自定义异常(Custom Exceptions):可以根据需要自定义异常类型,以便更好地表示特定的错误场景。 ```csharp public class MyCustomException : Exception { // 自定义异常的定义 } ``` 5. 异常处理最佳实践: - 只捕获你知道如何处理的异常,避免捕获所有异常。 - 在合适的层次捕获和处理异常,避免在每个方法中都使用try-catch块。 - 记录异常信息,以便进行故障排除和日志记录。 - 在catch块中避免使用空的catch语句,至少输出或记录异常信息。 - 使用finally块进行清理和资源释放操作。 - 使用using语句来确保及时释放使用了IDisposable接口的对象。 ```csharp try { using (var resource = new MyDisposableResource()) { // 使用资源的代码 } } catch (Exception ex) { // 处理异常的代码 } ``` 以上是一些常见的C#错误处理和异常处理的技术和原则。合理地使用异常处理机制可以提高应用程序的健壮性和可靠性,减少潜在的错误和问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值