tags:

views:

211

answers:

3

Would it be benefical to add a generic way to add info to a 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);
}

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

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

The extra info could print (one per line) between the message and stack list.

Benefits: 1. Would not require creating new Throwables just to add extra information. 2. Stack traces would not have multiple layers of cause traces (and therefore be easier to read) 3. Reduce cost of creating extra stack traces.

A: 

In general, I think that it is better to use the standard idioms in cases like this. In this case, the standard idiom is to wrap the exception, like this:

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

Also, in general it is best not to catch generic Exceptions. If you want to catch and add information to RuntimeException, then do that, and create a new RuntimeException. Otherwise, think carefully about which checked exceptions you want to catch and throw.

Avi
+3  A: 

Chained exceptions already take care of removing redundant stack frames. That is, you'll only see a given stack frame listed once. It's a matter of opinion, but I'd consider lack of a chained exception a drawback.

Discouraging extension of RuntimeException would be good. This might help in that regard.

Intervening stack frames may wish to add their own context as the stack unwinds. That could lead to clobbering of properties. There should be a mechanism for dealing with that, such as a stack of values for a given property name.

This will never happen in core Java, but there's nothing stopping you from using this convention for your own Exception classes.

erickson
This wouldn't remove chained exceptions -- just add an alternative when you don't want to change the Throwable class.Clobbering: Maybe a List of String lines is better.
James A. N. Stauffer
+1  A: 

As usual, with Exceptions, it's very dependent on the scenario. Although you should try and be specific to which Exceptions you're catching, you also want to be explicit as to the reason for exceptions in the current scope and not augment exceptions thrown from another scope. If you have nothing to add which can help the caller and can't perform some action in response to the specific exception, just let it propagate. If there is information from your scope that will be pertinent to the caller, throw your exception with your information, chained to the caught exception. The key here is scope. Always produce results from the current scope and allow other scopes to do the same.

nicerobot