0

I have some inline code in an aspx file that executes:

<dd><%=  encode(Listing.Address.Line1) %> </dd>

Problem is, under certain circumstances the Listing object will be null and therefore references to properties such as Address will throw an exception. How do I handle that exception? I basically want to ignore it: catch it, and then proceed with regular execution/rendering of page.

0

3 Answers 3

5

Do a null check. It is almost always better to test for the conditions of an exception that you expect might happen rather than handle it. The runtime has to do more work to throw and handle an exception than it does to just test for it in the first place and deal with it accordingly.

<%= encode(Listing != null && Listing.Address != null ? Listing.Address.Line1 : string.Empty) %> 

And be sure to check address just in case. Short circuiting is your friend, the order matters in the &&ing.

Without seeing a broader picture, I would suggest that your viewmodel, if you have one, has a method that does this automatically for you. This kind of stuff gets ugly in the view if you have it everyplace.

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

1 Comment

Oops, didn't see yours and posted almost the exact same thing. +1.
1

Assuming the problem to be fairly simple where Listing isn't null, and therefore, all it underlying attributes aren't null either you can type something like this:

<%= encode( (Listing ?? (new Listing(AddressObj))).Address.Line1 ) %>

Your can write the Listing class here with a constructor such that Address.Line1 will always have value.

Now if your problem is fairly complex, where in you Listing object may have a valid instance but its underlying attribute may not: the best way is to wrap the encode method into another method or property which will return the expected result, and call that in the markup.

public string EncodedAddress
{
    get
    {
        if (Listing == null)
            return string.Empty;
        if (Listing.Address == null)
            return string.Empty;
        return encode(Listing.Address.Line1);
    }
}

In the markup you do something like:

<%= EncodedAddress %>

Comments

-3

Use this

<%= if(Listing.Address.Line1 != null)
      { 
         encode(Listing.Address.Line1)
      }
%> 

2 Comments

This will throw the exact same exception if listing is null, as he describes. You are not testing the existence of Listing before you do this.
Also, an if statement doesn't return a value, so it can't be used in <%= %> tags.

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.