如何处理NullReference异常c#

时间:2013-09-05 13:48:25

标签: c# exception exception-handling nullreferenceexception

我正在尝试处理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块中处理它。

请帮助我如何抛出异常。

2 个答案:

答案 0 :(得分:6)

  

我正在尝试处理NullReference异常,但我很困惑   处理那个

你已经检查过customer is null了。你需要检查到位。

抛出异常是很昂贵的,并且知道如果TaxId无效可能导致此异常并非真正exceptional的情况,那么在我看来验证用户输入时会出现问题。

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

答案 1 :(得分: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);
}

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