6

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.

7
  • You dont have to throw it, If there any null exception it will be caught by the catch block Commented Sep 5, 2013 at 13:50
  • I don't understand the question... you're already throwing/catching the exception.. what do you need? Commented Sep 5, 2013 at 13:50
  • 11
    It is very expensive to throw and catch exceptions though. The entire stack has to be unwound. You are better off testing for NULL and then taking appropriate action. You application will perform better. Commented Sep 5, 2013 at 13:51
  • 1
    @BillGregg That's the recommended approach if it depends on external (e.g., user) input. Otherwise, if this really is an error then the readibility of an Exception might be worth more than the performance impact. Commented Sep 5, 2013 at 13:54
  • 2
    @user2619542 - If you are trying to process data that is null then your flow of your program is wrong. If you do not check if something is null BEFORE you do something to it, then your program flow is broken, because nothing should happen to nothing. Commented Sep 5, 2013 at 14:26

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

8 Comments

when the customer object is null, it still continuing the execution and generating the output. I wondered even if i given a wrong taxid it still producing the output, rather it should given to the eventhandler so that it will display all the messages.
@user2619542 - but you've allowed the program to throw an exception when you know this is a possibility (Not really exceptional). As mentioned in my answer and as BillGreg pointed out, throwing exceptions is expensive, a simple check to see if the object is not null will suffice.
Have you seen the code which i put in comments like //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; //} here i am checking whether the returned object is null or not. If null then i am handling this to the event handler. Now my manager told that use try-catch blocks to handle the null exception.
@user2619542 - Its really simple. Just make sure the customer is never null, if it is null, then do nothing with the null data, and display a custom error message. This does not mean you shouldn't catch the exception, if you don't, that particular exception would simply result in the program crashing.
Your manager is giving you bad advice. You shouldn't use Try Catch blocks to handle program flow. That's what we learned in programming 102.
|
1

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.

2 Comments

When we throw the exception in if(customer == null) can we catch that in other method?
Personally I think you have to catch ex when you can reasonably handle them. see blogs.msdn.com/b/ericlippert/archive/2008/09/10/… for some idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.