File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is this controlling flow with exceptions?

 
Raf Szczypiorski
Ranch Hand
Posts: 383
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I have this doubt - I know exceptions should not be used to cotrol application flow. So, please gurus answer me this question: suppose I have some class that reads in a configuration from a properties file, and one of the properties is a port number. I want to enforce it to be in the valid range, so I write this piece of code:

So, is line 17 doing something it should not be doing? If the number is not in the range, it throws an exception, so that it is handled in a common parsing handler. Is there a better way? I can for example use a simple if to test if it is a valid port, and only then do some work with it, but if I wanted to display a message to the user or sth.
(Note this is a simple code to illustrate the question, not production quality code ;d)
 
Campbell Ritchie
Sheriff
Pie
Posts: 47216
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Difficult to be certain because I only had a very quick look at your code, but passing a non-existent port number probably does justify throwing an Exception.

NumberFormatException is probably not the best Exception to throw, however; see if you can find (or create) a PortNumberException or similar.
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Campbell - in general this sort of thing looks appropriate, though it would be better to have a different error message. There's nothing wrong with the number format of a number like 123456 or -1 - they just aren't valid port numbers. Additionally, I would say that it looks silly to intentionally throw and catch an exception within the same method. After all, it would be trivial to rewrite the method to avoid the exception entirely, and I think the result would be shorter & clearer, as well. Also I think it might well look similarly silly if the throw and catch were just within the same class - though there may be some situations where this is necessary. But if the throw and catch were in different classes entirely, then I think throwing and catching an exception would make perfect sense here.
 
Rob Spoor
Sheriff
Pie
Posts: 20368
43
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IllegalArgumentException comes to mind. Which adds a bonus as NumberFormatException is a subclass of IllegalArgumentException.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic