[4404] in java-interest
finally statement
daemon@ATHENA.MIT.EDU (James Knighten(am one!))
Fri Dec 22 03:45:01 1995
Date: Fri, 22 Dec 95 15:47:25 JST
From: knightjm@pms.mmlab.toshiba.co.jp (James Knighten(am one!))
To: java-interest@java.sun.com
I've been reading about exception handling in the JDK-beta2 tutorial (/java/
exceptions/* group of html files). I read the reasons for having a finally
block at the end of a try-catch block in /java/exceptions/finally.html, but
I still don't understand the need for a finally block. Since control will be
passed to the statement following the try-catch block anyway, why should I
bother typing in a finally block? Is it simply a matter of semantics because
the cleanup done in a finally block is associated with the items in the try
block? Could it be that all code in an exception handling method should
be put in the try-catch-finally block? Could it be that I've had too much
coffee (Java)? Here's the particular code example from /java/exceptions/
putItTogether.html...
public void writeList() {
PrintStream pStr = null;
try {
int i;
System.err.println("Entering try statement");
pStr = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("OutFile.txt")));
for (i = 0; i < size; i++)
pStr.println("Value at: " + i + " = " + victor.elementAt(i));
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (pStr != null) {
System.err.println("Closing PrintStream");
pStr.close();
} else {
System.err.println("PrintStream not open");
}
}
}
Lastly, I'm assuming that if an error occurs inside the finally block it
will be treated like any other exception that occurs outside the try block.
thanks, jim
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com