[Advanced-java] How To Determine The Appropriate Exception?
Silvio L. de Morais
shirubio at yahoo.com
Fri Aug 8 16:48:41 2003
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?
--- David Rosenstrauch <david.rosenstrauch@aleri.com>
wrote:
> On Friday 08 August 2003 10:15 am, KCE wrote:
> >
> > Yeah, in fact, you can use the Exception base class:
> >
> > try {
> > myObject.myMethod();
> > } catch(Exception e) {
> > e.printStackTrace();
> > }
> >
> > Just try to avoid doing this whenever possible! Its
> > really easy to wind up with exceptions flying
> everywhere
> > and NO IDEA where they came from!!!
>
>
> Yes, use the exception class.
>
> But IMHO your response is off-base on 2 other points:
>
> 1) "Just try to avoid doing this whenever possible!" I
> couldn't disagree
> more. There's no need to "try to avoid" using
> exceptions. Use them when
> they're appropriate - they make for a clean flow of code.
> Don't use them
> when they're not appropriate. I don't think I ever
> experienced this issue of
> "exceptions flying everywhere and NO IDEA where they came
> from", and I've
> been coding in Java for 8 years.
>
> 2) You should never do this:
>
> } catch(Exception e) {
> e.printStackTrace();
> }
>
> "Swallowing" an exception deep down in some method in the
> call stack instead
> of propogating it up the call stack is a really bad idea.
> It makes for
> extremely buggy code where something dies deep down
> somewhere, but the
> calling code (whether GUI or server) never knows about it
> or handles it
> properly. Furthermore, "handling" an exception by just
> printing the stack
> trace is pretty useless. A stack trace printed to the
> console is of no use
> to an end user. (Assuming they even know where to look
> to read it.)
>
>
> DR
>
> _______________________________________________
> Advanced-java mailing list
> Advanced-java@lists.xcf.berkeley.edu
>
http://lists.xcf.berkeley.edu/mailman/listinfo/advanced-java
=====