pek said:
But I can avoid using a finally block and still accomplish the same
goal. For example, this code :
public String readString() {
String oneLine;
try {
FileReader theFile = new FileReader( fileName );
BufferedReader fileIn = new BufferedReader( theFile );
oneLine = fileIn.readLine();
} catch (Exception e) {
// Oversimplified catch clause
}
fileIn.close();
return oneLine;
}
This will not compile, because of the scope of fileIn,
because oneLine might not be initialized and because
BufferedReader.close() can throw an IOException. And even
If you really want to e.g. return null in case of an exception
instead of passing the exception you are not making sure that
the resource is closed all the time. If an Error instead of
an Exception occures (e.g. an OutOfMemoryError), you won't
be inside the catch-clause leaving the resource unclosed
until the garbage collector comes around,
In general you see finally in code-blocks like this:
public String readLine() throws IOException{
Reader fileIn = null;
try{
FileReader fr = new FileReader(fileName);
fileIn = new BufferedReader(InputStreamReader(fr, "8859_1"));
return fileIn.readLine();
}
finally{
if (fileIn != null){
try{
fileIn.close();
catch(Exception e){}
}
}
}
So the method can pass an occured IOException but still
makes sure that all resources are closed. If you want
to do this without the use of finally you would have
to do something like this:
try{
...
}
catch(Throwable t){
if (fileIn != null){
try{
fileIn.close();
}
catch(Exception e){}
}
if (t instanceof ThreadDeath){
throw (ThreadDeath) t;
}
if (t instanceof RuntimeException){
throw (RuntimeException) t;
}
if (t instanceof IOException){
throw (IOException) t;
}
throw (IOException) new IOException("an exception occured while " +
"accessing the resource").initCause(t);
}
Quite unreadable, isn't it?
and this code:
public String readString() {
String oneLine;
try {
FileReader theFile = new FileReader( fileName );
BufferedReader fileIn = new BufferedReader( theFile );
oneLine = fileIn.readLine();
fileIn.close();
return oneLine;
} catch (Exception e) {
// Oversimplified catch clause
fileIn.close();
return oneLine;
}
}
This is actually the same, i.e. it won't compile and duplicates
code violating the DRY-principle.
is the same as this:
public String readString() {
String oneLine;
try {
FileReader theFile = new FileReader( fileName );
BufferedReader fileIn = new BufferedReader( theFile );
oneLine = fileIn.readLine();
return oneLine;
} catch (Exception e) {
// Oversimplified catch clause
return oneLine;
} finally {
fileIn.close();
}
}
This is no the same, because it won't compile for the additional
reason, that the method doesn't return a value all the time.
Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)
Always remember: The answer is forty-two, there can only be wrong
questions!