try/catch 不适用于 using 语句
try
{
using (response = (HttpWebResponse)request.GetResponse())
// Exception is not caught by outer try!
}
catch (Exception ex)
{
// Log
}
编辑:
// Code for binding IP address:
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
//
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
IPAddress address;
if (retryCount < 3)
address = IPAddress.Parse("IPAddressHere");
else
{
address = IPAddress.Any;
throw new Exception("IP is not available,"); // This exception is not caught
}
return new IPEndPoint(address, 0);
}
try
{
using (response = (HttpWebResponse)request.GetResponse())
// Exception is not caught by outer try!
}
catch (Exception ex)
{
// Log
}
EDIT:
// Code for binding IP address:
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
//
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
IPAddress address;
if (retryCount < 3)
address = IPAddress.Parse("IPAddressHere");
else
{
address = IPAddress.Any;
throw new Exception("IP is not available,"); // This exception is not caught
}
return new IPEndPoint(address, 0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可以想象,如果您在
using
块中创建一个单独的线程,就会发生这种情况。如果那里抛出异常,一定要在那里处理它。否则,这种情况下的外部 catch 块将无法处理它。I could imagine this can happen if you are creating a separate thread within the
using
block. If an exception is thrown there, be sure to handle it there as well. Otherwise, the outer catch block in this case won't be able to handle it.使用后还有更多代码吗? using 需要一条语句或在 using 语句之后有一个块 { }。在下面的示例中,using 语句内的任何异常都将被 try..catch 块捕获。
Do you have more code after the using? The using needs one statement or a block { } after the using statement. In the example below any exception inside the using statement will be caught with the try..catch block.
这很好用。您将看到 Console.WriteLine() 打印出一个异常
,如果您的意思是在 using 内部抛出异常,那么这可以很好地工作。这还将生成一个控制台语句:
This works fine. You'll see an exception getting printed by the Console.WriteLine()
And if you meant that the exception gets thrown inside the using, this works fine to. This will also generate a Console statement:
using 关键字与 try-catch-finally 相同,http://msdn。 microsoft.com/en-us/library/yh598w02.aspx。基本上,您在 try-catch 中嵌套了一个 try-catch-finally ,这就是您可能如此困惑的原因。
你可以这样做...
The using keyword is the same as try-catch-finally, http://msdn.microsoft.com/en-us/library/yh598w02.aspx. Basically, you have a try-catch-finally nested inside of a try-catch which is why you're probably so confused.
You could just do this instead...