考虑以下C#代码结构(S0-S3是任意代码块的占位符):
try
{
S0;
}
catch (Exception ex)
{
S1;
}
finally
{
S2;
}
S3;
如果S1在catch
处理程序内部抛出异常,那么finally
中的S2仍将执行(但S3不会执行)。
问题
假设S1不能抛出异常,在finally
块中放置S2而不是将其放置在try/catch/finally之外,在S3之前是否有意义?
示例
try
{
// Do something that might throw
}
catch (Exception ex)
{
// Save the exception to re-throw later
// NB: This statement cannot throw an exception!
this.cachedException = ex;
}
finally
{
S2;
}
S3;
finally块有什么意义吗?如果在严格假设catch块内部不会抛出异常的情况下,以下代码不是等价的吗:
try
{
// Do something that might throw
}
catch (Exception ex)
{
// Save the exception to re-throw later
// NB: This statement cannot throw an exception!
this.cachedException = ex;
}
// No finally block needed (?)
S2;
S3;
次要问题
更新:如果接受上述两个代码块在所声明的假设下是等效的,那么考虑到答案中有关代码清晰度的反馈,将S2和S3组合在finally
块内是否更好(且等效)?
try
{
// Do something that might throw
}
catch (Exception ex)
{
// Save the exception to re-throw later
// NB: This statement cannot throw an exception!
this.cachedException = ex;
}
finally
{
S2; // Put S2 and S3 together inside the `finally` block to guard against
S3; // future changes in the `catch` filter, or handling code.
}