ewok ewok - 1 month ago 9
Java Question

Java: catch exception, perform finally, then rethrow exception

I have a serialization task I want to perform. It contains the following block of code:

try {
reader.readObject();
} finally {
reader.close();
}


The issue I have is that
readObject()
may throw several different types of exceptions. What I would like to do is, if there is an exception, catch it, store it, close the reader, then raise a wrapper exception with the caught exception as the cause. Like this:

try {
reader.readObject();
} catch (Exception e) {
// something
} finally {
reader.close();
throw new SerializationException(e);
}


I can't figure out how to deal with scoping here.
e
will be out of scope by the finally block, as will anything I declare in the catch block. The best I can come up with is this:

SerializationException caught = null;
try {
reader.readObject();
} catch (Exception e) {
caught = new SerializationException(e);
} finally {
reader.close();
if (caught != null){
throw caught;
}
}


But I don't really like that. It's creating an artifact (
caught
) that will only ever be used in exceptional scenarios, and will sit around uselessly until the end of scope if things work properly. It just doesn't feel right.

Is there a better way to handle this kind of thing?

Answer

You can do it from the catch block:

try {
  reader.readObject();
} catch (Exception e) {
  // something
  throw new SerializationException(e);
} finally {
  reader.close();
}

Note that finally is always executed (apart from a few corner cases), even if an exception is thrown in the try block.