Try Catch Finally. Try with resources

 Finally - ensures us that this part of code(I mean code inside Finally braces) will be executed.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class MyFileWriter {
public static void writeToFile(String text, String file) throws Exception {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(bw);
bw.write(text);
} catch (IOException ex) {
System.err.format("IOException: " + ex);
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
System.err.format("IOException " + ex);
}
}
}
}
Here we can see that if something happens in first catch then finally will be executed.
If we do not put finally some error may occur in first catch and then finally will not be 
executed.


Try with resources. If any class implements Closeable then we may utilize Try with resources.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class MyFileWriter {
public static void writeToFile(String text, String file) throws Exception {
try (FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(text);
} catch (IOException ex) {
System.err.format("IOException: " + ex);
}
}
}
After try automatically IDE calls close part of this classes. So that we do not need finally 
part.

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class