最后需要在哪里? [英] Where the finally is necessary?
问题描述
我知道如何最终使用try-catch-catch。但是我没有得到最终使用
的优势,因为我总是可以将代码放在try-catch块之后。
是否有明确的示例?
I know how to use try-catch-finally. However I do not get the advance of using finally
as I always can place the code after the try-catch block.
Is there any clear example?
推荐答案
更新:这实际上不是一个很好的例子回答。另一方面,也许 是一个很好的答案,因为它说明了最终
成功的一个完美示例,开发人员(即我)可能会失败以确保正确清理。在下面的代码中,考虑抛出 other 而不是 SpecificException
的异常的情况。然后,第一个示例仍将执行清除操作,而第二个示例将不执行清除操作,即使开发人员可能会认为我捕获了异常并对其进行了处理,因此可以确定后续代码将运行。
Update: This is actually not a great answer. On the other hand, maybe it is a good answer because it illustrates a perfect example of finally
succeeding where a developer (i.e., me) might fail to ensure cleanup properly. In the below code, consider the scenario where an exception other than SpecificException
is thrown. Then the first example will still perform cleanup, while the second will not, even though the developer may think "I caught the exception and handled it, so surely the subsequent code will run."
每个人给出使用 try
/ finally
不捕获
。即使您抛出异常,使用 catch
来 这样做仍然有意义。请考虑要返回值的情况*。
Everybody's giving reasons to use try
/finally
without a catch
. It can still make sense to do so with a catch
, even if you're throwing an exception. Consider the case* where you want to return a value.
try
{
DoSomethingTricky();
return true;
}
catch (SpecificException ex)
{
LogException(ex);
return false;
}
finally
{
DoImportantCleanup();
}
上述无 a 最终
(在我看来)可读性较差:
The alternative to the above without a finally
is (in my opinion) somewhat less readable:
bool success;
try
{
DoSomethingTricky();
success = true;
}
catch (SpecificException ex)
{
LogException(ex);
success = false;
}
DoImportantCleanup();
return success;
*我确实认为<$ c的更好例子$ c> try / catch
/ finally
是重新抛出异常时(使用 throw
,不 throw ex
抛出-但这是另一个主题) $ c> catch 块,因此最终
是必需的,因为如果没有它,则在 try $ c $之后进行编码c> /
捕获
无法运行。通常使用 IDisposable
资源上的 using
语句来完成此操作,但并非总是如此。有时清理不是专门的 Dispose
调用(或者不仅仅是 Dispose
调用)。
*I do think a better example of try
/catch
/finally
is when the exception is re-thrown (using throw
, not throw ex
—but that's another topic) in the catch
block, and so the finally
is necessary as without it code after the try
/catch
would not run. This is typically accomplished with a using
statement on an IDisposable
resource, but that's not always the case. Sometimes the cleanup is not specifically a Dispose
call (or is more than just a Dispose
call).
这篇关于最后需要在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!