【发布时间】:2009-10-31 14:13:00
【问题描述】:
通常我遇到的情况是,我必须吞下 catch/finally 块中的清理代码抛出的异常,以防止吞下原始异常。
例如:
// Closing a file in Java
public void example1() throws IOException {
boolean exceptionThrown = false;
FileWriter out = new FileWriter(“test.txt”);
try {
out.write(“example”);
} catch (IOException ex) {
exceptionThrown = true;
throw ex;
} finally {
try {
out.close();
} catch (IOException ex) {
if (!exceptionThrown) throw ex;
// Else, swallow the exception thrown by the close() method
// to prevent the original being swallowed.
}
}
}
// Rolling back a transaction in .Net
public void example2() {
using (SqlConnection connection = new SqlConnection(this.connectionString)) {
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = command.BeginTransaction();
try {
// Execute some database statements.
transaction.Commit();
} catch {
try {
transaction.Rollback();
} catch {
// Swallow the exception thrown by the Rollback() method
// to prevent the original being swallowed.
}
throw;
}
}
}
假设记录任何异常不是方法块范围内的选项,而是由调用example1() 和example2() 方法的代码完成。
吞下close() 和Rollback() 方法抛出的异常是个好主意吗?如果不是,那么有什么更好的方法来处理上述情况,以免异常被吞没?
【问题讨论】:
-
我使用的模式与您的
example1几乎完全相同。 -
对于实现
IDisposable(通常是这种情况)的资源,我有implemented an extension method,它结合了您的example1的逻辑以及其他策略。