How to add status information without writing repeated code while catching multiple Java exceptions?

I read a few other posts, like this one , to avoid repetition in Java blocks catch. Apparently I really want “multi-user”, but after seeing that Java 7 does not exist yet, is there a good template that allows me to add state to my exceptions and then re-throw them without catching the kitchen sink ?

In particular, I have code that calls library calls that may throw exceptions, but do not provide enough context for successful debugging. I found that I had a problem, and then went in, ending the library call in try / catch, catching a specific exception, and then adding additional status information to the block catchand throwing the caught exception again. Then I repeat this loop again and again, every time you find a new error condition to register. I'm ending with

try {
  make_library_call();
}
catch (SomeException e){
  throw new SomeException ("Needed local state information is " + importantInfo, e);
}
catch (SomeOtherException e){
  throw new SomeOtherException ("Needed local state information is " + importantInfo, e);
}
catch (YetAnotherException e){
  throw new YetAnotherException ("Needed local state information is " + importantInfo, e);
}

etc. I think I really would like to see more in the lines

try {
  make_lib_call();
}
catch(Exception e){
  e.AddSomeInformationSomehow("Needed Info" + importantInfo);
  throw e;
}

, e - , , , , . , -

try{
  make_lib_call();
}
finally {
  if (/*an exception happened*/)
    logger.debug("Some state info: " + importantInfo);
}

, . / ?

+3
2

, , , ( - ) . , , , , , , Java 7.

final rethrow, .

+2

:

boolean isOk = false;
try{
  make_lib_call();
  isOk = true;
}
finally {
  if (!isOk)
    logger.debug("Some state info: " + importantInfo);
}
+2

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


All Articles