Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: How to get type from the input?
|
Posted: Aug 15, 2003 1:18 PM
|
|
> Sure you could write a method using the wrapper methods > you listed as long as you are use try/catch blocks to > catch the NumberFormatExceptions that will be thrown.
That was exactly what I meant by "try" (I made it bold, but that probably wasn't explicit enough, since in both cases it was next to other text that was bold).
> The issue really is whether you should. I think that it > is generally viewed that exceptions should be used for > exceptional events, not to control the flow of a program.
Generally, perhaps, but not always. In this case I like the idea of having the same code that does the tranformation also do the validation. You can do all kinds of checks on the string's format to try and determine whether parseInt() or parseFloat() will like it and still be wrong. Regardless of how much pre-checking you do, you still need to catch the NumberFormatException. Additionally, your pre-checking may be flawed and you might filter out some things that would have been acceptible (for example, if you forgot to include the minus sign in your filter).
By the way, the NumberFormat class has some things that will help with this problem.
> If I remember correctly the Joshua Bloch "Effective Java" > book has an item on this, pretty much saying the same > thing. I don't have the book in front of me so I can't be > more specific.
I don't think Josh is a doctrinaire, so I'm sure he couched this advice in the "prefer this technique" form, as he does commonly in Effective Java (this is a good practice that was also used in Scott Meyer's Effective C++ books).
I think what he is arguing against is capricious use of exceptions. For example, this code works fine, but is a bad use of exceptions:
import java.io.PrintStream;
public class BadUseOfException
{
public static void main(String args[])
{
printNumberList( new int []{ 4, 3, 2, 1 }, System.out );
}
static void printNumberList( int [] numbers, PrintStream stream )
{
try
{
for( int i = 0; i < Integer.MAX_VALUE; i++ )
stream.println( i + ". " + numbers[i] );
}
catch( ArrayIndexOutOfBoundsException aioobe )
{
stream.println("That's all, folks!");
}
}
}
It is bad because it confuses the reader. Someone who sees this code will be a bit perplexed that you didn't use the array length and waste time to figure out why you are using this unusual technique.
|
|