捕获所有未处理异常

本文关键字:未处理 异常 | 更新日期: 2023-09-27 18:02:11

我将在我的Winforms应用程序中捕获所有未处理的异常。以下是缩短的代码:

[STAThread]
static void Main()
{
    if (!AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe"))
    {
        Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod);
    }
    Application.Run(new frmLogin());
}
private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t)
{
    Exception ex = t.Exception;
    StackTrace trace = new StackTrace(ex, true);
    var db = new MyDataContext();
    Error error = new Error();
    error.FormName = trace.GetFrame(0).GetMethod().ReflectedType.FullName;
    error.LineNumber = trace.GetFrame(0).GetFileLineNumber();
    error.ColumnNumber = trace.GetFrame(0).GetFileColumnNumber();
    error.Message = ex.Message;
    db.Errors.InsertOnSubmit(error);
    db.SubmitChanges();
    if (new frmError(ex).ShowDialog() != DialogResult.Yes)
        System.Diagnostics.Process.GetCurrentProcess().Kill();
}

问题是,有时FormName, LineNumber和ColumnNumber没有正确返回。下面是我有时得到的结果:

  --FormName--          --Line/Column--    --Message--
System.Linq.Enumerable       0  0   Sequence contains no matching element
System.RuntimeMethodHandle   0  0   Exception has been thrown by the target of an invocation.
System.Number                0  0   Input string was not in a correct format.
System.Number                0  0   Input string was not in a correct format.
System.ThrowHelper           0  0   Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

可以看到,LineNumbers和ColumnNumbers都是0。

我该如何解决这个问题?

捕获所有未处理异常

我该如何解决这个问题?

当给定模块没有.pdb时,堆栈跟踪信息必然不能包含文件名、行号或列号。

要获得它们,需要确保. net .pdb可用并已加载。有许多可用的资源描述了如何做到这一点。参见无法进入。net框架源代码,例如,或高级。net调试- pdb和符号存储。您可以使用您喜欢的网络搜索引擎来查找其他资源。

我还会注意到您将类型名称描述为"FormName",这是不正确的。它只是表单抛出异常时的表单名称。未处理异常总是bug,通常由框架或其他库代码抛出,类型不会是表单。

我还将提到捕获所有异常仅对诊断错误有用。这不应该用来试图提高程序的总体可靠性(除非更好的诊断可以允许您修复错误)。当发生未处理的异常时,应该将其记录下来,然后终止该进程。允许进程在发生未处理的异常后继续执行对您的数据是危险的,并且可能导致对错误修复的自满。