views:

637

answers:

8

Can you please let me know if my code is correct? I'm studying for my test in two hours so I dont really have time to write an application to test it.

Question is: if I have a JLabel with a number as its label. simply a label that says 34 for example. I want to extract the number from the label. but i need to handle exceptions, i.e it's not a number, it can be a letter.

would my code below handle the exception correctly?

JLabel label = new JLabel("34");
int extracted;

this is what i would do

try{
    extracted = Integer.parseInt(extracted.getText());
    System.out.println("the number was: "+ extracted);
}
catch(IOException exception){
    System.out.println(label.getText() + " is not a number");
}
+5  A: 

I would check the documentation for Integer.parseInt()

Furthermore, I'd strongly recommend setting up a test project in whatever IDE you use so you can test this stuff yourself with a rapid turnaround! Even if it's a vim/javac+make script.

Brian Agnew
+2  A: 

It's almost correct, except that you're catching the wrong exception; parseInt() throws a NumberFormatException.

Daniel Lew
A: 

You should catch NumberFormatException. Otherwise, fine.

Randolpho
+1  A: 

Integer.parseInt() throws a NumberFormatException not an IOException.

cletus
A: 

The javadoc for Integer.parseInt() states that it can throw a NumberFormatException, not an IOException.

The code you have written will not compile, because IOException is a checked exception which cannot be thrown by any of the code in the try block.

Simon Nickerson
+5  A: 

Close, but catching an IOException won't work because that exception type is not thrown by the parseInt() method. Try catching a NumberFormatException instead:

try{
    extracted = Integer.parseInt(extracted.getText());
    System.out.println("the number was: "+ extracted);
} catch(NumberFormatException exception) {
    System.out.println(label.getText() + " is not a number");
}
craig
thanks this is correct
+1  A: 

NumberFormatException is a RunTimeException (unchecked), for compilation purposes, you don't really have to write it in the catch portion.

If what you are trying to do is determine if the user will type numbers in the JTextField (and not any other character), you should look at regex (Regular expressions), instead of catching this one using the try .. catch mechanism.

Ted Heich
Why in earth would you want to do that? Regex have GOT to be slower, and are certainly more fallible. You would lose internationalization and any other things the built-in implementation gives you. Although a test would be better than an exception, anything is better than regex
Bill K
Well yes, I agree, but there wasn't anything in the code sample and on the original question which pertains to internationalization. And I based recomm on regex just by second guessing his intentions, which is to test if the characters inputted were numerics. I respect your opinion on regex though.
Ted Heich