0

I am trying to make a simple method which test to see if a provide String contains only numbers, to do this I am trying to use try and catch (just learnt it and I would like to practise putting it to use) where I try to parseInt() the given String and if there's an error (not a number) then it will catch it and return false;

    public boolean checkNumber(String s){
    try(Integer.parseInt(s)){
        return true;
    }
    catch(Exception E){
        return false;
    }
}

It says I have a misplaced constructor.

4
  • 1
    You actually should be using regex expressions... But that is outside the scope of your question. Commented Mar 4, 2014 at 16:01
  • To elaborate on skiwis comment, a string representation of a number falling ouside the range of an integer will throw an exception when parsed by Integer.parseInt Commented Mar 4, 2014 at 16:04
  • The syntax you are using is for "try with resources". You might want to look it up, can be useful in other circumstances. Commented Mar 4, 2014 at 16:06
  • @Khaelid On everything that is not a number, an Exception will be thrown and caught, which are generally a big order of magnitude slower than simple checks. Exceptions are for exceptional situations. Commented Mar 4, 2014 at 16:09

3 Answers 3

6

Catch the correct exception and move the try check into the block rather than in brackets.

 try {
       Integer.parseInt(s);
       return true;
    }
    catch(NumberFormatException e){
        return false;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This is true but it'd be defensive programming to enforce a null check, it could be expected for a NPE to throw if s is passed in as null as just blindly checking for it could hide other errors.
1

That's not the correct syntax for try. Use

try
{
    Integer.parseInt(s);
    return true;
}
catch (Exception ex)
{
    return false;
}

Comments

1

syntax error

try {
  Integer.parseInt(s);
} catch(Exception e) {
  return false;
}
return true;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.