Sam*_*tar 2 c# exception-handling
我使用以下代码:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
但是当对象为null时,我得到以下内容:
System.NullReferenceException未由用户代码处理HResult = -2147467261 Message =对象引用未设置为对象的实例.
有没有办法可以捕获此异常并将其返回给调用程序.现在它给了我上面的错误,Visual Studio停了下来.
Cla*_*edi 11
处理你的具体案件的正确方法是
if (myObject != null)
{
string json = myObject.ToJSONString();
// other logic
}
else
{
// handle the situation where myObject is null
}
Run Code Online (Sandbox Code Playgroud)
这样做,你就可以避免触发异常.
归档时间: |
|
查看次数: |
96 次 |
最近记录: |