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)
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.