Today in college we talked a little bit about try
, catch
and finally
.
I got confused about these two examples:
PrintWriter out = null;
try {
out = new PrintWriter(...); // We open file here
} catch (Exception e) {
e.printStackTrace();
} finally { // And we close it here
out.close();
}
What is the difference between closing the file in finally
and if we just did it this way:
PrintWriter out = null;
try {
out = new PrintWriter(...); // We open file here
} catch (Exception e) {
e.printStackTrace();
}
out.close();
This piece of code after catch will always execute.
Can you give me some good examples about the differences between when we use finally
and when we put the code after catch? I know that finally will always execute, but the program will also keep running after catch block.