简体   繁体   中英

Try and Catch using Integer.parseInt() syntax error [Java]

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.

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;
    }

That's not the correct syntax for try. Use

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

syntax error

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM