通常我会遇到这样的情况:在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()
方法抛出的异常是一个好主意吗?如果不是,有什么更好的处理上述情况的方式,以便异常不被忽略?
IDisposable
接口的资源(通常情况下),我已经实现了一个扩展方法,将您的example1
的逻辑与其他策略结合起来。 - Douglas