【问题标题】:Problem with Exception caught without argument无参数捕获的异常问题
【发布时间】:2011-04-08 17:32:42
【问题描述】:

这个事件、事件包装器和处理程序遇到了一个奇怪的问题:

public delegate void StatusUpdateHandler(string message, Exception exc, SeverityLevel severity);

public event StatusUpdateHandler StatusUpdate;

private void FireStatusUpdate(string message)
{
    if (this.StatusUpdate != null)
        this.StatusUpdate(message, null, SeverityLevel.None);
}

void scanDocProcessor_StatusUpdate(string message, Exception exc, SeverityLevel severity)
{
    try
    {
        if (exc != null)
        {
            if (severity >= setSevLevel)
                this._logger.Log(message + Environment.NewLine + exc.ToString(), LogEntryType.Emergency, "OCR Submission Processor Status Update", true);
            else
                this._logger.Log(message + Environment.NewLine + exc.ToString(), LogEntryType.Error, "OCR Submission Processor Status Update", false);
        }
        else if (severity >= setSevLevel)
        {
            this._logger.Log(message, LogEntryType.Info, "OCR Submission Processor Status Update", true, true);
        }
        else
            this._logger.Log(message, LogEntryType.Info, "OCR Submission Processor Status Update", false);
    }
    catch (Exception)
    {
        EventLog.WriteEntry("Russia OCR Submission Processor", "Could not log status update event: " + exc.ToString(), EventLogEntryType.Information);
    }
}

在几分钟的时间里,_logger 停止记录消息,而我在事件日志中收到了这些消息:

无法记录状态更新事件:System.NullReferenceException:对象引用未设置为对象的实例。 在 ScannedService.scanDocProcessor_StatusUpdate(字符串消息,异常 exc,SeverityLevel 严重性) 在 ScannedService.Processor.FireStatusUpdate(字符串消息) 在 ScannedService.Processor.ProcessQueue(Object Object)

我很困惑事件日志在应该编写 exc.ToString() 时如何获得这样的堆栈跟踪。我查看了 IL 的 scanDocProcessor_StatusUpdate 方法没有初始化 Exception 对象。除此之外,我不知道如何抛出 nullreferenceexception。当 Log 方法确实捕获到异常时,它会吞下它或用“throw;”重新抛出它。 message 参数永远不会为空,并且 SeverityLevel 是一个枚举。

【问题讨论】:

  • 除非您打算退出程序,否则切勿捕获Exception。

标签: c# .net exception


【解决方案1】:

您在else 条件之一中引发异常,其中ecx 为空。在catch 块中,您假设ecx 不为空,这会生成另一个 隐藏原始异常的异常。

您可以使用以下方法使您的日志语句为空安全:

EventLog.WriteEntry("Russia OCR Submission Processor", 
    String.Format("Could not log status update event: {0}", exc), EventLogEntryType.Information);

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多