[Advanced-java] How To Determine The Appropriate Exception?
Nikolaos Giannopoulos
nikolaos at solmar.ca
Sat Aug 9 01:35:09 2003
> From: advanced-java-bounces@lists.xcf.berkeley.edu
> [mailto:advanced-java-bounces@lists.xcf.berkeley.edu]On Behalf Of David
> Rosenstrauch
>
>
> I can't argue specifically with your rationalization, but I guess
> I feel like using ClassCastExceptions in this way smells a bit funny
> to me - although I can't pinpoint specifically why.
I think what I dis-like most about this implementation is the fact that by
using using ClassCastException error handling one would expect that it's
because the author would consider a class cast exception an error condition
i.e. that there should not be an instnace of any other class returned (other
than the expected one) and if it isn't what I expect it to be then there's a
problem - but the default value exposes its true purpose which is that the
author does indeed expect that the exception may occur in normal flow and
has even provisioned for it.
The big problem is none of this is obvious on the surface and one would
expect that ClassCastException was being used to handle error conditions.
Better off using instanceof IMO and not confusing future maintainers of your
code i.e. even if you did document this I would have to do a double take
upon seeing it to fully understand what it is your trying to do and why your
doing so in this manner.
With instanceof its a different story as the result is a boolean value upon
which you clearly specify what to do if it not an instance of this class -
and thus clearly demonstrate that you would handle a class that is outside
the expected by supplying a default value - signaling that it is not an
error condition but more of an out of (expected) bounds condition.
--Nikolaos
> On Friday 08 August 2003 11:39 am, Silvio L. de Morais wrote:
> > I like this kind of discussions.
> > To keep on the same subject, I would like your opinions on
> > a simple technique I use sometimes.
> > Whenever I have a method that receives a generic base class
> > as parameter (could even be Object), and I have to call a
> > specific method defined on a derived class, I do this:
> >
> > public void m1(ClassA ob)
> > {
> > String x;
> > try {
> > x =
> > ((ClassB)ob).someMethodOfClassBNotDefinedInClassA();
> > }
> > catch (ClassCastException cce) {
> > {
> > x = "Default Value";
> > }
> > …
> > }
> >
> > My rationalization of this is: 'Most of the time the cast
> > will be correct, and I will not have to use the more
> > expensive "instanceof" operator all the time'. But I was
> > criticized before on a code review because it is not a good
> > use of Exceptions.
> > What do you guys think?
>
> _______________________________________________
> Advanced-java mailing list
> Advanced-java@lists.xcf.berkeley.edu
> http://lists.xcf.berkeley.edu/mailman/listinfo/advanced-java
>