Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do you improve this - exception handling ?

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote this code:

But I smell something fishy with line marked X. It
just doesn't seem right. What do you think ?
Pho
 
Mikael Jonasson
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Pho
[This message has been edited by Pho Tek (edited August 16, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic