[Advanced-java] How To Determine The Appropriate Exception?
David Rosenstrauch
david.rosenstrauch at aleri.com
Fri Aug 8 21:52:45 2003
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 generally wind up doing the instanceof check (it's not THAT expensive) or -
even better - using polymorphism: have Class B implement that method and
return the default value there.
DR
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?