据我所知,使用像try/catch/finally这样的工程,所以我期望如果在using语句中发生异常,它会被捕获(这有点奇怪,因为那也意味着异常是默默吃了)。 using语句应该捕获异常并调用Dispose
方法,但是,这种情况不会发生。我已经设计了一个简单的测试来演示这个问题。为什么在应该像try/catch/finally那样运行时抛出异常?
这里是我强迫异常using语句里面发生:
using (TcpClient client = new TcpClient())
{
// Why does this throw when the using statement is supposed to be a try/catch/finally?
client.Connect(null);
}
一个例外是抛出由client.Connect()
(这意味着它没有被使用的语句或捕获,它正在重新抛出) :
System.ArgumentNullException: Value cannot be null.
Parameter name: remoteEP
at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
at DotNETSandbox.Program.Main(String[] args) in C:\path\to\Sandbox\Program.cs:line 42
据a Microsoft article on the topic,using语句可能如果Dispose
方法抛出抛出。
然而,当我正在关注的使用模式,显而易见的是,Dispose方法不抛出:
TcpClient c2 = new TcpClient();
try
{
c2.Connect(null);
}
catch (Exception e)
{
// We caught the null ref exception
try
{
// Try to dispose: works fine, does not throw!
((IDisposable)c2).Dispose();
}
catch (Exception e2)
{
Console.WriteLine(e2.ToString());
}
Console.WriteLine(e.ToString());
}
我有点困惑,因为我期待using
表现得像一试/抓住。有谁能解释为什么会发生这种情况吗?
,终于阻止,终于不是试试抓住。异常仍会抛出使用块。 – 2012-03-06 19:44:26
为什么_what_发生?你是否期望'using'语句默默地吃掉异常? – SLaks 2012-03-06 19:45:40
@SLaks由于某种原因,我留下的印象是“使用”有一个声明,我从来没有真正投入过多的想法,直到现在。我总是抓住例外,它从来没有真正担心过我,但在阅读文章后,我意识到我错过了一些东西。 – Kiril 2012-03-06 19:56:33