Java Io Ugly Try-Finally Block

Java io ugly try-finally block

This is the correct idom (and it works fine):

   InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(inputFileName);
out = new FileOutputStream(outputFileName);
copy(in, out);
finally {
close(in);
close(out);
}

public static void close(Closeable c) {
if (c == null) return;
try {
c.close();
} catch (IOException e) {
//log the exception
}
}

The reason this works fine is that the exception thrown before you got to finally will be thrown after your finally code finishes, provided that your finally code doesn't itself throw an exception or otherwise terminate abnormally.

Edit: As of Java 7 (and Android SDK 19 - KitKat) there is now a Try with resources syntax to make this cleaner. How to deal with that is addressed in this question.

java try finally block to close stream

It seems a bit clunky.

It is. At least java7's try with resources fixes that.

Pre java7 you can make a closeStream function that swallows it:

public void closeStream(Closeable s){
try{
if(s!=null)s.close();
}catch(IOException e){
//Log or rethrow as unchecked (like RuntimException) ;)
}
}

Or put the try...finally inside the try catch:

try{
BufferedReader r = new BufferedReader(new InputStreamReader(address.openStream()));
try{

String inLine;
while ((inLine = r.readLine()) != null) {
System.out.println(inLine);
}
}finally{
r.close();
}
}catch(IOException e){
e.printStackTrace();
}

It's more verbose and an exception in the finally will hide one in the try but it's semantically closer to the try-with-resources introduced in Java 7.

advice on nested Java try/finally code sandwiches

It is nice.

No major complaints, minor things off the top of my head:

  • a little performance burden
  • you need to make some things final for the Compensation to see them. Maybe this prevents some use-cases
  • you should catch exceptions during compensate and continue running Compensations no matter what
  • (bit far-fetched) you could accidentally empty out the Compensation queue at run-time due to a programming error. OTOH programming errors can happen anyway. And with your Compensation queue, you get "conditional finally blocks".
  • don't push this too far. Within a single method it seems okay (but then you probably don't need too many try/finally blocks anyway), but don't pass Compensation queues up and down the call stack.
  • it delays compensation to the "outermost finally" which could be a problem for things that need to be cleaned up early
  • it only makes sense when you need the try block only for the finally block. If you have a catch block anyway, you might just add the finally right there.

return in try-catch's finally block in java. Is there any good point in this example?

Is there really any point in adding a finally block here?

The answer to this is a resounding "no": putting a return statement in the finally block is a very bad idea.

I just add the return null inside the catch block, which would execute the same behavior, or am I wrong?

It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning null unconditionally the way the original code does, the code with the return inside the catch block would return null only on errors. In other words, the value returned in the try branch would be returned to the caller unless there is an exception.

Moreover, if you add return null after the catch block, you would see the correct effect of returning null on exception. I would go even further, and put a single return in the method, like this:

response or = null;
try {
or = //gives it a value
log.info(or.toString());
} catch ( Exception e) {
e.printStackTrace();
}
return or;

Discover if exception is thrown in finally part of try-finally block

It's something that has long frustrated me.

I normally declare a variable exceptionThrown=true at the top and set it to false just before returning. Then you can test that in the finally handler. I think that's better than catching and re-throwing because the latter approach will mess up the stack trace.

I'm surprised neither Java nor C# has a better way of handling this

try catch in finally section

The pattern of needing try/catches in finally methods is unfortunately a recurring pattern in Java 6 and before. I would argue that it actually IS a bad practice, but not one that you can really avoid in Java 6 (see below for Java 7).

An addition problem is that any new exceptions thrown in the finally block will override exceptions that were thrown before reaching this block.

In Java 7 there is specifically for the cases where resources need to be closed (the majority of the use cases for try/finally/try/catch constructs) the new try-with-resources construct. This will also capture both the primary and secondary exceptions.

Using this construct is thus now a best practice in JDK 7 and yes, the code you show is thus a bad practice in Java 7.

eclipse asks me to surround with try/catch in finally block - possible to disable it?

This is not an Eclipse error, it is a Java compiler error. Eclipse is merely reporting the Java compilation error for you. There is no way to "turn it off" as the code does not compile without the try/catch clause. It is a safety feature in Java that forces you to handle commonly thrown Exceptions.

Methods have Exceptions in their signature. For example, InputStream.close() throws an IOException, forcing you to handle it in a try/catch block.

public void close() throws IOException {
...

Throwing an Exception is a way of telling the program that a significant problem - that must be handled - has occurred.

My question is: is it possible to remove this error in eclipse and use try/catch when I need it otherwise not instead of eclipse telling me to do try/catch add.

No, it is not possible.

(Since I am already trying to avoid exception by replacing try/catch with if/else as possible).

You should generally never try to replace try/catch blocks with if/else blocks. They are two distinct features with distinct purposes.

Exceptions are an essential Java feature. Read about it and understand it.



Related Topics



Leave a reply



Submit