通常,在处理Java IO代码时,这是我写的
FileOutputStream out = null;
try
{
out = new FileOutputStream("myfile.txt");
// More and more code goes here...
}
catch (Exception e)
{
}
finally
{
// I put the close code in finally block, to enture the opened
// file stream is always closed even there is exception happened.
if (out != null) {
// Another try catch block, troublesome.
try {
out.close();
} catch (IOException ex) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,当我尝试关闭文件流时,我需要处理另一个try ... catch块.
看起来很麻烦:(
有什么办法可以避免吗?将close代码放在非finally块中感觉不舒服,因为其他代码引起的异常将无法调用"close".
通常我会遇到这样的情况:我必须吞下catch/ finallyblock中清理代码抛出的异常,以防止吞噬原始异常.
例如:
// 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 …Run Code Online (Sandbox Code Playgroud)