未处理的运行时错误 c#

本文关键字:运行时错误 未处理 | 更新日期: 2023-09-27 18:31:24

 private void SetConnection(string id, string classCode)
    {
        try
        {
            _connection = new SqlConnection { ConnectionString = Settings.Default.CurrentConnection };
            _connection.Open();
            while (_connection.State == ConnectionState.Connecting || _connection.State == ConnectionState.Closed)
                Thread.Sleep(1000);
            _command = new SqlCommand(Settings.Default.EligibilityBenefitSP, _connection);
            if (_command != null) _command.CommandType = CommandType.StoredProcedure;
            _command.Parameters.Add("@ClassCode", SqlDbType.NVarChar).Value = classCode;
            _command.Parameters.Add("@Id", SqlDbType.NVarChar).Value = id;
        }
        catch (Exception e)
        {
            throw new Exception(e.Message + " " + Settings.Default.EligibilityBenefitSP);
        }
    }
   public Collection<EligibilityClassBenefit> ExtractEligibilityClassBenefit(string id, string classCode)
    {
        SetConnection(id, classCode);
        Collection<EligibilityClassBenefit> eclassBene = new Collection<EligibilityClassBenefit>();
        SqlDataReader reader = null;
        try
        {
            _command.CommandTimeout = 420;
            if (_connection.State == ConnectionState.Open)
                reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
            else
                throw new Exception("Connection Closed");
                /* no data */
                if (!reader.HasRows) return null;
                while (reader.Read())
                {
                    EligibilityClassBenefit eligibilityClassBenefit = new EligibilityClassBenefit
                    {
                        EffectiveDate                = reader["EffectiveDate"].ToString(),
                        EndDate                      = reader["EndDate"].ToString(),
                        InitialEffectiveDate         = reader["InitialEffectiveDate"].ToString(),
                        IsAdministrativeServicesOnly = reader["IsAdministrativeServicesOnly"].ToString(),
                        EffectiveProvision           = reader["EffectiveProvision"].ToString(),
                        ProbationPeriod              = reader["ProbationPeriod"].ToString(),
                        UnderwritingType             = ExtractUnderwritingType(id),
                        ProbationPeriodUnit          = reader["ProbationPeriodUnit"].ToString(),
                        StateOfIssue                 = reader["StateOfIssue"].ToString(),
                    };
                    BenefitData benefitData = new BenefitData();
                    eligibilityClassBenefit.Benefit = benefitData.ExtractBenefit(reader, id, classCode);
                    EligibilityClassBenefitBusinessLevelData eligibilityLevelData = new EligibilityClassBenefitBusinessLevelData();
                    eligibilityClassBenefit.EligibilityClassBenefitBusinessLevelNodes = eligibilityLevelData.ExtractBenefitBusinessLevel(reader);
                    eclassBene.Add(eligibilityClassBenefit);
            }
            return eclassBene;
        }
        catch (Exception e)
        {
            throw new Exception(e.InnerException.Message + e.InnerException.StackTrace);
        }
        finally
        {
            //if (_connection.State == ConnectionState.Open) _connection.Close();
            if (reader != null) reader.Close();
            _command.Dispose();
        }
    }

上面是一个代码示例,其中包含一个常规异常捕获,但是当我运行此程序时,它会随机中断和处理应用程序日志的异常,并带有 .net 运行时错误 null 引用异常。

一点背景...这是一个在午夜在应用程序服务器上自动运行的控制台应用程序。它针对不同的 SQL Server 2008 框执行存储过程。我们过去常常在执行维护任务时被 sql 服务器丢弃连接时收到这些错误,现在情况已不再如此。我需要得到一个更具体的错误。我不明白为什么它会绕过 catch 子句而只是抛出一个未经处理的运行时异常。这是什么意思?它发生在任意数量的代码点上,而不仅仅是这个。这只是最后一个爆炸的例子

未处理的运行时错误 c#

在捕获异常时,还会将它们抛出以供调用方处理。现在,您发布的代码中没有入口点,因此很难看到此代码段之外发生了什么。

但是,大胆猜测,我对 NullRef 异常起源的建议是你这样做的地方:e.InnerException.Message .

InnerException属性很可能为 null,这将导致 NullRef 异常。然而,这并不是真正的例外。由于上述错误,导致程序最终出现在异常处理程序中的真正异常是隐藏的。

如果要包含来自 InnerException 的消息,请首先检查它是否为 null。

编辑:

这样做:

catch (Exception e)
{
    throw new Exception(e.InnerException.Message + e.InnerException.StackTrace);
}

捕获任何异常并将其重新抛出以进行处理。如果调用代码未处理异常,即未将调用包装在 try-catch 块中,则运行时会将异常视为未处理。

实际上,做你正在做的事情根本没有意义。除非您打算对问题执行某些操作,否则不要捕获异常。您在这里所做的只是弄乱调用方的 StackTrace,因为您正在重新抛出一个新的异常。如果你觉得由于某种原因你必须插手并重新投掷,你应该这样做:

catch (Exception e)
{
    throw new Exception("I have a good reason for interrupting the flow", e);
}

请注意,异常实例是在重新引发的异常的构造函数中传递的。这最终将成为内部的例外。

关于你的异常策略,这也是非常不必要的:

if (_connection.State == ConnectionState.Open)
    reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
else
    throw new Exception("Connection Closed");

如果连接关闭,ExecuteReader 方法已经抛出了一个InvalidOperationException,这比你抛出的Exception更具体。如果您打算对此执行某些操作,请稍后捕获更具体的异常。现在,您将异常用作程序逻辑的一部分,这不是好的做法。