try/catch 不适用于 using 语句
本文关键字:using 语句 适用于 不适用 catch try | 更新日期: 2023-09-27 17:57:01
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);
}
我可以想象,如果您在using
块中创建单独的线程,就会发生这种情况。如果在那里抛出异常,请确保也在那里处理它。否则,在这种情况下,外部捕获块将无法处理它。
class TestClass : IDisposable
{
public void GetTest()
{
throw new Exception("Something bad happened"); // handle this
}
public void Dispose()
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
using (TestClass t = new TestClass())
{
Thread ts = new Thread(new ThreadStart(t.GetTest));
ts.Start();
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
使用后你有更多的代码吗? using 需要一个语句或 using 语句后面的块 { }。 在下面的示例中,using 语句中的任何异常都将被 try 捕获。捕获块。
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
....
}
}
catch (Exception ex)
{
}
这工作正常。 您将看到 Console.WriteLine() 打印的异常
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
如果你的意思是异常被抛入使用,这很好用。 这也将生成一个控制台语句:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
throw new ApplicationException("Something wrong inside the using.");
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
return new Bar();
// throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
using 关键字与 try-catch-finally 相同,http://msdn.microsoft.com/en-us/library/yh598w02.aspx。 基本上,你有一个 try-catch-finally 嵌套在一个 try-catch 中,这就是为什么你可能如此困惑。
你可以这样做...
class Program
{
static void Main(string[] args)
{
HttpWebResponse response = new HttpWebResponse();
try
{
response.GetResponse();
}
catch (Exception ex)
{
//do something with the exception
}
finally
{
response.Dispose();
}
}
}