Writing a catch block with cleanup operations in Java

I was unable to find any recommendations on catch blocks in Java that include some cleanup operations that themselves may throw exceptions.

A classic example is one stream.close()that we usually call in a sentence finally, and if it throws an exception, we either ignore it by calling it in a try-catch block or declaring that it will be returned.

But overall, 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 le1) {
  //ignore?
  //log?
  }
  throw new ApiException(le); //I must throw le
}

But this means that I will need to do some log analysis to understand why the cleanup failed.

If I did:

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

This results in a loss lethat made me enter the catch block in the first place.

What are some of the idioms that people use here?

  • throws?
  • ?
+3
2

, finally - - close()... , - , API ? , 99% , .

, , , . . ( , initCause()).

, - . , , , . , , , ( , ).

, , . , ( - IO, , close() ).

+3

finally. , :

Exception ex = new Exception(le.stackTrace());
0

Source: https://habr.com/ru/post/1744584/


All Articles