Though the question is generic, I would mention the scenario which sparked the query.
Scenario:
I am interested in analyzing a large number of strings (numeric ones in particular). Therefore, my first job is to filter out those ones which contain even a single character other than numbers.
A simple way to do this is (in Java):
for (String val : stringArray){
try{
int num = Integer.parseInt(val);
doSomething(num);
}
catch(NumberFormatException nfe){}
}
Another point which I must mention is that there are only about 5% of the strings in the array which are purely numeric. Thus there would be, in short, a lot of catching involved.
What I was wondering about was that whether this was an efficient way in terms of design or should I be thinking of other ways to do the same?
Conclusion based on answers: Exceptions are indeed expensive and it is not a very good design practice to use them as a form of control statement.
Therefore, one should try and look for alternatives wherever possible and if still exceptions seem to be clearer/easier, one should document it well.
What you do here is inherently correct as there is no other standard way in java to check if a string is numeric.
If a profiling proves you that this operation is too long, you could try to do it yourself as in the parseInt method but the JVM won’t be able to do the same optimizations so I don’t recommend it. You’ll see that the JVM is heavily optimized to handle exceptions and that it does this job very well.
As a curiosity, here are a few ways to do it in java :
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java
with links to other languages, but your solution is the standard and idiomatic one and I doubt you’ll find a big difference by rewriting it as in the example :
Using this, in my opinion, would be a typical case of premature optimization leading to a less maintainable code.