如何处理 NullReference 异常 c#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18638143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:49:32  来源:igfitidea点击:

How to handle a NullReference Exception c#

c#exceptionexception-handlingnullreferenceexception

提问by user2619542

I am trying to handle a NullReference Exception, but i am confused how to handle that. Here is my sample code where a NullReference exception is raised:

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

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

Now i am handling this in the following method

现在我用以下方法处理这个

 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);
            }
        }

I the previous case i am writing like if(customer == null) now i should get rid of that code so that i can handle it in the catch block.

我以前写的情况就像 if(customer == null) 现在我应该摆脱该代码,以便我可以在 catch 块中处理它。

Please help me how to throw that exception.

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

回答by Darren

I am trying to handle a NullReference Exception, but i am confused how to handle that

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

Well you already have by checking if customer is null. You need that check in place.

好吧,您已经通过检查 if customer is null。你需要到位检查。

Throwing an exception is expensive, and knowing that this exception can be caused if the TaxIdis not valid is not really an exceptionalcase, it's a problem in validating the user input in my opinion.

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

If an object can return null, simply check that object's value before trying to access the properties/methods. I would never allow an exception to be thrown and interrupt the standard program flow just to catch an Exception and log it.

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

回答by Alessandro D'Andria

I'd do something like

我会做类似的事情

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);
}

The caller is responsable to handle exceptions and to validate args that sends.

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