DaveAKing / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Helper method for Throwable.initCause() in Throwables #1401

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
If you want to throw an exception with a cause, but the exception does not have 
a constructor that accepts a cause argument, you can use Throwable.initCause(), 
but this destroys method chaining because of the return type "Throwable".

So you have to write something like this:

try {
  ... 
} catch (SomeException e) {
  NumberFormatException nfe = new NumberFormatException("Invalid number");
  nfe.initCause(e);
  throw nfe;
}

With the following helper method this code could be shortened and made more 
readable:

<X extends Throwable> X withCause(Throwable cause, X t) {
  t.initCause(cause);
  return t;
}

try {
  ... 
} catch (SomeException e) {
  throw withCause(e, new NumberFormatException("Invalid number"));
}

Name and order of arguments are debatable, of course.

There are several exceptions in the Java API that have no constructor with a 
cause argument, so there this method would be helpful. Examples are 
NumberFormatException, ArithmeticException, and IndexOutOfBoundsException.

In a comment to another issue 
(https://code.google.com/p/guava-libraries/issues/detail?id=1382#c8) it was 
also mentioned that the cause as the last constructor parameter (as is common 
for exceptions that do have such a parameter) is not well readable. The 
proposed method could also be make code more readable and emphasize the 
addition of a cause, even if the exception would already provide the necessary 
constructor.

Original issue reported on code.google.com by phwend...@gmail.com on 8 May 2013 at 8:59

GoogleCodeExporter commented 9 years ago
When a Throwable doesn't accept a cause there are two possibilities:

1. It's very rare to have a cause exception, so the workaround is fine
2. It's common to have a cause exception and the creator of that Throwable 
class just messed up.

The examples you cite are solidly in case #1, and even for hypothetical 
examples in case #2 the proper solution is that the Throwable class itself 
should be fixed.

Methods like this exist only to paper over bad API decisions in other libraries 
and have no other discernible purpose. We decided long ago that it's not part 
of Guava's mission in life to try to address such cases.

Original comment by kevinb@google.com on 9 May 2013 at 8:23

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<issue id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:12

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:08