General way to add information to Throwable without creating a new Throwable

Would it be helpful to add a generic way to add information to Throwable without creating a new Throwable?

I often see code like this:

try {
  foo();
} catch(Exception e) {
  throw new Exception(e.getMessage() + " extra info=" + blah, e);
}

      

Wouldn't it be better to add Throwable.setProperty (String key, String value) instead so that the code above becomes the following?

try {
  foo();
} catch(Exception e) {
  e.setProperty("extra info", blah);
  throw e;
}

      

Additional information can print (one line at a time) between the message and the stack list.

Advantages: 1. It would not be necessary to create new Throwables just to add additional information. 2. The stack trace will not have multilayer traces (and therefore easier to read) 3. Reduce the cost of creating additional stack traces.

+1


source to share


3 answers


Bound exceptions already take care of removing redundant stack frames. That is, you will only see one stack frame listed once. This is a matter of opinion, but I believe there is no flaw in the exception chain.

Failure to expand RuntimeException

would be good. It can help in this regard.



Intermediate stack frames may wish to add their own context as the package decays. This can lead to confusion of properties. There must be a mechanism to deal with this, such as a stack of values ​​for a given property name.

This won't happen in Java core, but there is nothing stopping you from using this convention for your own Exception classes.

+3


source


As usual with Exceptions it is very script dependent. While you should try and specify which exceptions you are using, you also want to be explicit about the reasons for exceptions in the current scope and not supplement exceptions written out from another scope. If you have nothing to add that can help the caller and cannot take any action in response to a specific exception, just allow it to propagate. If there is information from your scope that would be relevant to the caller, throw your exception onto your information, chained to the thrown exception. The key here is scope. Always create results from the current volume and let other areas do the same.



+1


source


In general, I think it's best to use standard idioms in such cases. In this case, the standard idiom is to wrap an exception, for example:

try {
  foo();
} catch (Exception e) {
  throw new MySpecificException("extra info=" + blah, e);
}

      

Also, it is generally best not to catch generic exceptions in general. If you want to catch and add information to the RuntimeException, do so and throw a new RuntimeException. Otherwise, think about what checked exceptions you want to catch and throw.

0


source







All Articles