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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With