Will the following finally clause be executed, if an exception is thrown by the PrintWriter?
try{
PrintWriter out = new PrintWriter(filename);
try {
//output
} finally {
out.close();
}
} catch {
//handle exception
}
If the PrintWriter throws an exception, then the nested try block will never get executed, but why the nested finally clause will still be executed, even it's nested and skipped?
Updates: I ran some tests, if an exception is thrown before the nested try clause, that nested finally will not be executed. If the exception is thrown inside the nested try clause, then the inner finally and the outter catch will be executed.
finallyblock is not related to your print writer statementPrintWriter implements AutoCloseableand therefore, you can just use atrywith resources liketry (PrintWriter out = new PrintWriter(filename)) { ... } catch { ... }where nofinallywill be needed (forout). What's inside the innertrythat could throw anException?