The Java beginners book contains the following code. This book also explains exceptions very well, and since I understood how the exception works, I had a question about the following code.
For some reason, if the FileWriter class throws an exception, writer.close()it will not be executed. Therefore, I believe that the best place to close the writer object is in the final block. Even before that, I saw a lot of code written in this way, where the resource will be closed in the try block itself. I think there is no point in this. Only when there is no exception, the resource will be closed.
Am I really wrong? What is the best way to close resources in java. Should we write code as follows?
public static void main(String[] args) {
try{
FileWriter writer = new FileWriter("file.txt");
writer.write("i am writing");
writer.close();
}catch(IOException e){
ex.printStackTrace();
}
}