YouReallyArentGonnaNeedThis
Inspired by discussions about exceptions, I scanned the Java source for JDK
1.1.5 and came across the following example of code that would be clearer
if written as if no exceptions could occur.
YouReallyArentGonnaNeedThis!
try {
...
} catch (InternalError e) {
throw new InternalError();
}
--
KielHodges
Maybe. However, the code is not a no-op. The exception object includes information - for example, a dump of the stack which it is created, and a description string. By replacing an old exception object with a new one you discard some information about the true point-of-error. Perhaps this was deliberate
InformationHiding.
If so, how else would you write it? Or would you just add a comment?
-- DaveHarris
throw new InternalError("names have been changed to protect the innocent");
Agreed, it is not a no-op. But I don't think it was
intentional
InformationHiding. If it were, I would
include a comment or
something. Hard to say exactly as
I have no clue why I am hiding the true point-of-error
anyway!
I found it in the clone() method of
SimpleTextBoundary
which extends
BreakIterator.
BreakIterator defines clone()
following Sun's usual idiom:
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
Basically, they are following what I call the
ImpossibleException idiom. The compiler believes that
the body of the method can throw a
CheckedException
(Clone
Not
Supported
Exception), but the programmer knows
better. She chooses to
ConvertExceptions, in this case
converting it into Internal
Error. This buys her two things.
First, she is
adding information: the bug in the
library, specifically. Secondly, clients of
BreakIterator aren't burdened with catching or declaring an
ImpossibleException.
SimpleTextBoundary follows suit, sort of:
public Object clone() {
try {
return super.clone();
} catch (InternalError e) {
throw new InternalError();
}
}
But this isn't the
ImpossibleException idiom! It adds
nothing.
My guess is that the author of
SimpleTextBoundary
originally coded the catch clause as in
BreakIterator, but
the compiler complained that Clone
Not
Supported
Exception
wasn't thrown within the try block. He investigated finding
that
BreakIterator threw
InternalError instead and changed
the catch accordingly.
--
KielHodges
One should also note that
InformationHiding is
inappropriate in this situation. An
InternalError when
attempting to clone a
SimpleTextBoundary should be reported
to the vendor as a bug. The programmer charged with
addressing the bug has (a small amount of) additional work
in order to locate the cause of the bug. --
KielHodges
See also
YouArentGonnaNeedIt