Writing catch block with cleanup operations in Java ...

Posted by kedarmhaswade on Stack Overflow See other posts from Stack Overflow or by kedarmhaswade
Published on 2010-05-08T02:18:06Z Indexed on 2010/05/08 2:28 UTC
Read the original article Hit count: 320

I was not able to find any advise on catch blocks in Java that involve some cleanup operations which themselves could throw exceptions.

The classic example is that of stream.close() which we usually call in the finally clause and if that throws an exception, we either ignore it by calling it in a try-catch block or declare it to be rethrown.

But in general, how do I handle cases like:

public void doIt() throws ApiException { //ApiException is my "higher level" exception
  try {
    doLower();
  } catch(Exception le) {
    doCleanup(); //this throws exception too which I can't communicate to caller
    throw new ApiException(le);
  }
}

I could do:

catch(Exception le) {
  try {
    doCleanup();
  } catch(Exception e) {
  //ignore?
  //log?
  }
  throw new ApiException(le); //I must throw le
}

But that means I will have to do some log analysis to understand why cleanup failed.

If I did:

catch(Exception le) {
  try {
    doCleanup();
  } catch(Exception e) {
    throw new ApiException(e);
  }

It results in losing the le that got me here in the catch block in the fist place.

What are some of the idioms people use here?

  • Declare the lower level exceptions in throws clause?
  • Ignore the exceptions during cleanup operation?

© Stack Overflow or respective owner

Related posts about java-exceptions

Related posts about exception-handling