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.

user2619542
  • 223
  • 1
  • 5
  • 11
  • You dont have to throw it, If there any null exception it will be caught by the catch block – Kurubaran Sep 05 '13 at 13:50
  • I don't understand the question... you're already throwing/catching the exception.. what do you need? – dcastro Sep 05 '13 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. – Bill Gregg Sep 05 '13 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. – dcastro Sep 05 '13 at 13:54
  • The best way to handle null exceptions is to make sure your data types are never null. This does not mean you shouldn't catch the exception to prevent the program from simply crashing. – Security Hound Sep 05 '13 at 14:16
  • @Ramhound Since we are importing it from an uploaded file we can't make sure. So there will be chance of entering a wrong taxid which indeed returns null as there is no customer with that particular taxId. – user2619542 Sep 05 '13 at 14:20
  • 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. – Security Hound Sep 05 '13 at 14:26

2 Answers2

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.

Darren
  • 68,902
  • 24
  • 138
  • 144
  • 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 Sep 05 '13 at 14:01
  • @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. – Darren Sep 05 '13 at 14:04
  • 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 Sep 05 '13 at 14:17
  • @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. – Security Hound Sep 05 '13 at 14:18
  • @user2619542 - Your question needs some work to make the read readable, you don't have to provide us with commented code, and if you do make it in its own code block. Furthermore why are you even going into an event if the data is null, you should do nothing with null data, because its a null. – Security Hound Sep 05 '13 at 14:20
  • @Ramhound: I edited my question. I included the commented lines because that's the earlier version which is working fine, but my manager told me to use try catch blocks instead of checking if(customer == null). – user2619542 Sep 05 '13 at 14:25
  • 3
    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. – Bill Gregg Sep 05 '13 at 14:29
  • A catch statement is your last defense to a crash. You should do both, no reason, if the catch never happens it costs nothing. – Security Hound Sep 05 '13 at 14:46
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.

Alessandro D'Andria
  • 8,663
  • 2
  • 36
  • 32
  • When we throw the exception in if(customer == null) can we catch that in other method? – user2619542 Sep 05 '13 at 15:50
  • Personally I think you have to catch ex when you can reasonably handle them. see http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx for some idea. – Alessandro D'Andria Sep 05 '13 at 16:42