在 try catch 中检查 null
我的 WCF 服务方法中有一个 try catch 块,其中包含对对象的 if 检查。对象“objRequest”作为服务操作输入参数出现。这是代码:
try
{
if (objRequest == null)
{
//the lines here dont execute even though objRequest is null
...
...
}
//remaining code here
}
catch
{
...
}
现在奇怪的部分来了。如果我将 if 检查放在 try 块之外,则 if 检查有效。
if (objRequest == null)
{
//This 'if' check returns true when outside the try block and the line now executes.
.....
....
}
try
{
//remaining code here
}
catch
{
...
}
在这里剪了一张图片来证明我所说的。如果对象为 null,为什么它会进入 else 块?
我觉得这很神奇,但不是很好。我在这里缺少什么?
I have a try catch block in my WCF service method that contains an if check on an object. The object 'objRequest' comes in as a service operation input parameter. This is the code:
try
{
if (objRequest == null)
{
//the lines here dont execute even though objRequest is null
...
...
}
//remaining code here
}
catch
{
...
}
Now comes the strange part. If I put that if check outside the try block, the if check works.
if (objRequest == null)
{
//This 'if' check returns true when outside the try block and the line now executes.
.....
....
}
try
{
//remaining code here
}
catch
{
...
}
Clipped an image here to prove what I am saying. If the object is null, why did it go into the else block?
I find this magical, and not in a good way. What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的屏幕截图清楚地显示该对象不为空,因为您可以看到其属性的值。这些属性都是空的,这让您感到困惑。
Your screenshot clearly shows that the object is not null since you can see the values of its properties. Those properties are all null which is what is confusing you.
这就是异常抛出/处理的工作原理。
That's how exception throwing/handling works.
这也应该有效:
This should also work:
问题中的示例代码没有显示捕获了哪个特定的 Exception 类,也没有显示 catch 块内发生了什么。也许您希望该方法抛出异常,但当您从 try 块内抛出异常时,它会被 catch 块捕获。但是,如果您从 try 块外部抛出异常,则该异常不会被捕获,而是会从方法中抛出给调用者。
The sample code in the question does not show which specific Exception class is caught and also, what happens within the catch block. Perhaps you expect the method to throw an exception but it gets caught in the catch block when you throw it from within the try block. However, if you throw the exception from outside the try block, it will not be caught and will be thrown out of the method to the caller.
看起来效果很好。
编辑:
在您提供的屏幕截图中,对象不为空,只是其中的属性
It seems to work fine.
Edit:
In the screenshot your provided the object is not null, just the properties inside it