Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a NullReference Exception c#

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:

 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.

Please help me how to throw that exception.

like image 963
user2619542 Avatar asked Sep 05 '13 13:09

user2619542


1 Answers

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

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

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

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.

like image 109
Darren Avatar answered Sep 29 '22 08:09

Darren