使用终于赶上来代替 [英] Using finally instead of catch
问题描述
我已经看到了这种模式,现在几次:
I've seen this pattern a few times now:
bool success = false;
try
{
DoSomething();
success = true;
}
finally
{
if (!success)
Rollback();
}
和我一直在想:为什么这更好的比使用捕回退?
And I've been wondering: Why is this better than using catch for rollbacks?
try
{
DoSomething();
}
catch
{
Rollback();
throw;
}
什么是确保变化的两种方法之间的差异被回滚上失败?
What are the differences between the two ways of making sure changes are rolled back on failure?
推荐答案
这里的明确目标是使还原
是叫任何错误的情况。这两个代码片段实现这一目标。第一次使用了最后,这始终运行,这验证尝试
块的最后一行顺利抵达。第二捕获任何错误,回滚事务,然后重新抛出被捕捉到的异常。无论是代码片段的结果是,抛出的异常将导致回滚,同时仍然向上冒泡到一个新的水平。
The clear goal here is to cause Rollback
to be called in the event of any error. Both code snippets accomplish this goal. The first uses a finally, which always runs, that verifies that the last line of the try
block was successfully reached. The second catches any errors, rolls back the transaction, and then re-throws the exception that was caught. The result of either snippet is that any exceptions thrown will result in a rollback while still bubbling up to the next level.
您提到,该项目从Java移植。在Java中,您可以 重新抛出异常相似你如何在C#中使用扔;
。您也可以抛出一个新的异常将依然保持调用堆栈(ET人)。第二个是一个位更清晰/ C#中简单(不以大量尽管)和第一有在Java中实际工作作为写入的优点。
You mentioned that the project was ported from Java. In Java, you can re-throw an exception similarly to how you can in C# using throw;
. You can also throw a new exception that will still maintain the call stack (et al). The second is a bit clearer/simpler in C# (not by a lot though) and the first has the advantage of actually working in Java as written.
这篇关于使用终于赶上来代替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!