6

我正在尝试处理 NullReference 异常,但我很困惑如何处理它。这是引发 NullReference 异常的示例代码:

 private Customer GetCustomer(string unformatedTaxId)
        {               
                return loan.GetCustomerByTaxId(new TaxId(unformatedTaxId));                
        }

现在我用下面的方法处理这个

 public void ProcessApplicantAddress(ApplicantAddress line)
        {
            try
            {
                Customer customer = GetCustomer(line.TaxId);
                //if (customer == null)
                //{
                //    eventListener.HandleEvent(Severity.Informational, line.GetType().Name, String.Format("Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported.", new TaxId(line.TaxId).Masked));
                //    return;
                //}
                Address address = new Address();
                address.AddressLine1 = line.StreetAddress;
                address.City = line.City;
                address.State = State.TryFindById<State>(line.State);
                address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
                }
            catch(NullReferenceException e)
            {
                //eventListener.HandleEvent(Severity.Informational, line.GetType().Name, String.Format("Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported.", new TaxId(line.TaxId).Masked));
                eventListener.HandleEvent(Severity.Informational, line.GetType().Name, e.Message);
            }
        }

我之前写的例子是 if(customer == null) 现在我应该去掉那个代码,以便我可以在 catch 块中处理它。

请帮助我如何抛出该异常。

4

2 回答 2

9

我正在尝试处理 NullReference 异常,但我很困惑如何处理

那么你已经通过检查 if 了customer is null。您需要该检查到位。

抛出异常是昂贵的,并且知道如果TaxId无效则可能导致此异常并不是真正的exceptional情况,在我看来,验证用户输入是一个问题。

如果一个对象可以返回null,只需在尝试访问属性/方法之前检查该对象的值。我永远不会允许抛出异常并中断标准程序流只是为了捕获异常并记录它。

于 2013-09-05T13:56:36.803 回答
1

我会做类似的事情

public void ProcessApplicantAddress(ApplicantAddress line)
{
    if (line == null)
    {
        eventListener.HandleEvent(Severity.Informational, line.GetType().Name, "a message");

        throw new ArgumentNullException("line");
     }

     Customer customer = GetCustomer(line.TaxId);

     if (customer == null)
     {
         eventListener.HandleEvent(Severity.Informational, line.GetType().Name, "a message");

         throw new InvalidOperationException("a message");
     }

     Address address = new Address();

     if (address == null)
     {
        eventListener.HandleEvent(Severity.Informational, line.GetType().Name, "a message");

        throw new InvalidOperationException("a message");
     }

     address.AddressLine1 = line.StreetAddress;
     address.City = line.City;
     address.State = State.TryFindById<State>(line.State);
     address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
}

调用者负责处理异常并验证发送的参数。

于 2013-09-05T14:03:14.003 回答