[Advanced-java] How To Determine The Appropriate Exception?
Silvio L. de Morais
shirubio at yahoo.com
Fri Aug 8 22:26:54 2003
I totally agree that the best practice would be to
implement the method on the base class,
but sometimes you don't have control over it. This trick is
valid only for such cases.
A good example is when you are coding a TableCellRenderer's
getTableCellRendererComponent method. The 'value' parameter
is Object, forcing you to cast it back to the real class.
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int col)
{
JTextField result = new JTextField();
// … more initialization
try {
IStatusInfo status = (IStatusInfo) value;
if (status.isPending())
{
result.setText(formatDate(status.getStatusEffectiveDate()));
result.setBackground(Color.yellow);
result.setForeground(Color.black);
}
// ... more cases
}
catch (ClassCastException cce)
{
result.setText("Not applicable");
}
return result;
}
Silvio
--- David Rosenstrauch <david.rosenstrauch@aleri.com>
wrote:
> 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?
>
> _______________________________________________
> Advanced-java mailing list
> Advanced-java@lists.xcf.berkeley.edu
>
http://lists.xcf.berkeley.edu/mailman/listinfo/advanced-java
=====