JDK-6524473 : Enhance initCause() function .
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 5.0
  • Priority: P5
  • Status: Closed
  • Resolution: Won't Fix
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2007-02-13
  • Updated: 2011-02-16
  • Resolved: 2007-02-13
Description
A DESCRIPTION OF THE REQUEST :
 intCause() is a new mechanism for chaining in JDK 1.4. In pre-1.4 version the cause was recieved in the constructor in major cases. There are two main usage of it, in the constructor of custom exception that receive cause or immediately after exception is initialize, initCause() was called to add the cause. The last one was used with "legacy exception" primarily, but not only. There problem is in last usage. initCause() returns Throwable, so explicit casting is needed.
For example, throw (AssertionError)new AssertionError("UnexpectedException occured. ").initCause(e).
 Otherwise, compiler is thinking that not AssertionError is thrown, but Throwable with all complications.
 I suggest to change Throwable, perhaps with use of generic, so initCause() will return this type, rather then Throwable, in order to avoid casting.

JUSTIFICATION :
 Generic make significant step in type safety. It is needed to make on more little step to remove unnecessary casting from initCause().


CUSTOMER SUBMITTED WORKAROUND :
try{
  doSomething();
}catch (Exception e){
  log.error("Something goes wrong, while it should be ok",e);
  throw (AssertionError)new AssertionError("UnexpectedException occured. ").initCause(e);
}

Comments
EVALUATION What you want for the return type of initCause is a self type, something the language does not support -- see 6479372. With the language as it exists there's no compatible change to initCause that will improve the use case in question. What you can do is override initCause in any subclass of Throwable that you write, and use a covariant return type. This doesn't fully solve the problem, but can make things a bit better. This can't be applied to existing exception classes across the board, sadly, for compatibility reasons.
13-02-2007