2

I am using the following code:

public static string ToJSONString(this object obj)
{
    using (var stream = new MemoryStream())
    {
        var ser = new DataContractJsonSerializer(obj.GetType());

        ser.WriteObject(stream, obj);

        return Encoding.UTF8.GetString(stream.ToArray());
    }
}

But when the object is null I get the following:

System.NullReferenceException was unhandled by user code HResult=-2147467261 Message=Object reference not set to an instance of an object.

Is there a way I could catch this exception and return it to the calling program. Right now it gives me the above error and Visual Studio comes to a stop.

9
  • 2
    I would throw an ArgumentNullException in this case or - if you don't want an exception - return null (or String.Empty). Commented Mar 14, 2014 at 12:48
  • 4
    Well, it would be better if you'd throw ArgumentNullException - but it's still going to be an exception which indicates a bug, and shouldn't be caught... basically the caller shouldn't be doing that. Commented Mar 14, 2014 at 12:48
  • 1
    Try catch for that exception ands raise a custom exception. BUT it's the calling program that do this, not the callee. Commented Mar 14, 2014 at 12:49
  • 2
    @ykb That is not true. You can definitely call an extension method on a null reference. Commented Mar 14, 2014 at 12:54
  • 2
    @ykb: object obj1 = null; string json = obj1.ToJSONString(); wouldn't throw a NullReferenceException. An extension method is a static method, you don't need an instance. Commented Mar 14, 2014 at 12:56

1 Answer 1

11

The correct way to handle your specific case would be

if (myObject != null)
{
     string json = myObject.ToJSONString(); 
     // other logic
}
else
{
     // handle the situation where myObject is null
}

Doing this, you're avoiding the exception to trigger.

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

1 Comment

Even after the edit, the assumption is now that the call can and should handle the exception. You could be right in this case, but if it were me I'd qualify my opening sentence, anything else is just swallowing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.