Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes How do you improve this - exception handling ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do you improve this - exception handling ?" Watch "How do you improve this - exception handling ?" New topic

How do you improve this - exception handling ?

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782

I wrote this code:

But I smell something fishy with line marked X. It
just doesn't seem right. What do you think ?


Mikael Jonasson
Ranch Hand

Joined: May 16, 2001
Posts: 158
There is nothing wrong with the code per-se. However, by throwing and catching just Exception, you can't be sure that it is that error that occures. In this limited case: sure. But it is good to do things right from the beginning. The fanciest way is to create your own exceptionclass that inherits Exception, and catch that. I case something else occures it will be caught (hopefulle) further up in the program.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

how about the case when length is exactly equal to explicit length. I usually would code something like:
Also, consider that when you throw your new Exception it gets caught by your second catch block. The end result of your code seems to be to hide the NumberFormatException, and to replace it with an IllegalArgumentException.

So how about throwing that instead of new Exception, and delete your second catch block?
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782

Thanks for your comments.
A couple of my comments:
1) This code is actually refactored from an existing codebase.
So as I went about refactoring it to suit my needs, I had
to come up with that nasty, throw new exception()
to control the flow. According to the signature of the method;
all exceptions need to be masked out as an IllegalArgumentException. So I'd prefer not to introduce another exception class into the mix.
2) (To: Mike Curwen) In the context of the method,
length==explicitLength is ok and is processed later on after this try-catch scope.
[This message has been edited by Pho Tek (edited August 16, 2001).]
I agree. Here's the link:
subject: How do you improve this - exception handling ?
It's not a secret anymore!