【发布时间】:2012-03-24 08:15:52
【问题描述】:
据我了解,使用类似于 try/catch/finally 的工作方式,所以我希望如果在 using 语句中发生异常,它会被捕获(这有点奇怪,因为这也意味着异常被默默吃掉了)。 using 语句应该捕获异常并调用Dispose 方法,但是,这并没有发生。我设计了一个简单的测试来证明这个问题。
这里是我强制在 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() 抛出了一个异常(意味着它没有被 using 语句捕获或被重新抛出):
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,如果Dispose方法抛出,using语句可能会抛出。
但是,当我遵循 using 模式时,很明显 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 表现得像一个 try/catch。谁能解释为什么会这样?
【问题讨论】:
-
using 语句的行为类似于 try, finally 块,而不是 try catch finally。异常仍然会抛出 using 块。
-
为什么会发生what?您是否希望
using语句默默地吃掉异常? -
@SLaks 出于某种原因,我留下的印象是
using有一个 catch 语句,直到现在我才真正投入过多的思考。我总是发现异常,它从来没有让我真正担心过,但在阅读了这篇文章后,我意识到我错过了一些东西。
标签: c# exception try-catch using-statement