computerboy
05-01-2003, 03:52
Mình là dân mới nghiên cứu Java, xin cho hỏi khối lệnh finally trong phần quản lí và bắt biệt lệ có ý nghĩa quan trọng như thế nào mà Java lại đưa vào ? (trong C++ không có)
Theo như "The Java Tutorial" của Java.Sun thì ..... xét đoạn chương trình sau:
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
} catch (ArrayIndexOutOfBound***ception e) {
System.err.println("Caught ArrayIndexOutOfBound***ception: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
và rằng:
"The need for a finally statement is not apparent until you consider the following: how does the PrintWriter in the writeList method get closed if you don't provide an exception handler for the ArrayIndexOutOfBound***ception and an ArrayIndexOutOfBound***ception occurs?"
Nhưng mình lại thấy rằng khối finally hầu như không có chức năng gì ở đây, vì ta có thể thay khối finally bằng "phần thân" của nó, tức là
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
là được !??!
Không biết nhân xét của mình có gì không đúng, nhờ các bạn chỉ giùm !!
Theo như "The Java Tutorial" của Java.Sun thì ..... xét đoạn chương trình sau:
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
} catch (ArrayIndexOutOfBound***ception e) {
System.err.println("Caught ArrayIndexOutOfBound***ception: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
và rằng:
"The need for a finally statement is not apparent until you consider the following: how does the PrintWriter in the writeList method get closed if you don't provide an exception handler for the ArrayIndexOutOfBound***ception and an ArrayIndexOutOfBound***ception occurs?"
Nhưng mình lại thấy rằng khối finally hầu như không có chức năng gì ở đây, vì ta có thể thay khối finally bằng "phần thân" của nó, tức là
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
là được !??!
Không biết nhân xét của mình có gì không đúng, nhờ các bạn chỉ giùm !!