今天在大学里我们谈到了一些关于try
、catch
和finally
的知识。我有点困惑这两个例子:
PrintWriter out = null;
try {
out = new PrintWriter(...); // We open file here
} catch (Exception e) {
e.printStackTrace();
} finally { // And we close it here
out.close();
}
使用 finally
关闭文件和直接关闭文件有什么区别?
PrintWriter out = null;
try {
out = new PrintWriter(...); // We open file here
} catch (Exception e) {
e.printStackTrace();
}
out.close();
在catch
后面的这段代码将会始终执行。
你能给我一些很好的例子来说明使用finally
和把代码放在catch
之后的区别吗?我知道finally
将始终执行,但程序也将在catch
块之后继续运行。
out.close()
会在这种情况下被执行吗?换句话说,仅仅打印堆栈跟踪并继续执行并不总是正确处理异常的方式。 - rmlanException
并不是一个好主意。你应该尽可能地捕获最具体的异常类型。 - Andy Turner