File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Is this controlling flow with exceptions? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is this controlling flow with exceptions?" Watch "Is this controlling flow with exceptions?" New topic

Is this controlling flow with exceptions?

Raf Szczypiorski
Ranch Hand

Joined: Aug 21, 2008
Posts: 383
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

Joined: Oct 13, 2005
Posts: 46337
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

Joined: Mar 05, 2008
Posts: 3028
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

Joined: Oct 27, 2005
Posts: 20271

IllegalArgumentException comes to mind. Which adds a bonus as NumberFormatException is a subclass of IllegalArgumentException.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Is this controlling flow with exceptions?
It's not a secret anymore!