是否有可能看到我的应用程序扔了多少"异常"?

kar*_*ara 0 .net c# exception-handling exception

我有一些(旧的,旧的)控制台应用程序,它们可以处理大型数据库并处理一些数据.在处理数据时,抛出并捕获异常.不幸的是,如果记录无效,这在某些情况下是有意的.

我想测量异常的数量是否在可接受的范围内.

处理100.000条记录,20条Exceptions捕获=>正常运行.

处理100.000条记录,10.000 Exceptions捕获=>这是一个问题.

例如,代码

static void Main(string[] args)
{
    DoSomething();

    int x = HowMuchErrorsDidICatch(); // This is where 

    Console.WriteLine("This run catched {0} Exception.", x);
}

// Some work to do..
static void DoSomething()
{
    for (int i = 0; i < 1001; i++)
    {
        try
        {
            // .. Processing some Data
            if (i % 10 == 0)
                throw new Exception("Something went wrong.");
        }
        catch (Exception ex)
        {
            errorCount++;
            // Handling the Exception
        }
    }
}

#region What i'm searching for
// I hope to get those number from .Net
static int errorCount = 0;
private static int HowMuchErrorsDidICatch()
{
    return errorCount;
}
#endregion
Run Code Online (Sandbox Code Playgroud)

由于现有代码的数量,不能修改每个catch-block.

有没有人知道从.Net获得捕获量的方法?

ang*_*son 5

您正在寻找的是AppDomain.FirstChanceException:

在运行时在应用程序域中搜索调用堆栈中的异常处理程序之前,在托管代码中抛出异常时发生.

以下是您的方案的示例代码:

AppDomain.CurrentDomain.FirstChanceException += (s, e) => errorCount++;
Run Code Online (Sandbox Code Playgroud)

注意:千万不能发挥创意与此事件处理程序代码.它绝不能抛出你不处理的异常.如果异常从此事件处理程序中冒出,则将以递归方式调用该事件.因此,我将保留上面显示的代码,不要尝试在此事件处理程序中记录异常或诸如此类的东西.

另外,我相信可以从多个线程调用事件处理程序,因此代码确实需要万无一失.在上面的场景中,如果你在许多线程上有很多异常,你可能最终会失去一些例外的计数,在这种情况下你可能想要将代码重写为:

AppDomain.CurrentDomain.FirstChanceException += (s, e) => Interlocked.Increment(ref errorCount);
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要确切的异常数量,可能只需要这样做.如果你只想得到一笔金额,请留下来++.