当前位置: 动力学知识库 > 问答 > 编程问答 >

java - To check an integer more than 0

问题描述:

I have the following setter:

public void setId(String id) {

try{

Integer partnerId = Integer.parseInt(id);

if (partnerId <= 0){

throw new NumberFormatException();

}

} catch(NumberFormatException e){

}

this.id = id;

}

Is it a good way to check if the passed argument is an integer more than 0?

网友答案:

Don't throw a NumberFormatException, because there was nothing wrong with the format if the string - it was simply out of range. The standard, and correct, exception to throw is IllegalArgumentException with a message. And as a general rule (which applies here), you shouldn't catch an excrotion, but do nothing with it.

Try this:

public void setId(String id) {
    if (Integer.parseInt(id) < 1){
        throw new IllegalArgumentException("id must be greater than zero:" id);
    }
    this.id = id;
}

Also:

  • removed the int variable since you don't use it exception for comparing
  • removed the try catch - just let the exception bubble out. If the client passed bad dara that's their problem
网友答案:

NumberFormatException states:

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

That's not the situation in your case, if you insist to throw an exception, implement your own class:

public class LowerThanZeroException extends Exception {
    public LowerThanZeroException() { super("Number is lower than zero"); }
}

Or simply use IllegalArgumentException.

I don't think try and catch is the best option for you (although this really depends on your logic), but consider using if statement as well.

Also note that catching an exception and doing nothing with it will actually hide the problem.

网友答案:

Make a custom exception for (partnerId <= 0) condition. but do catch number format exception as well because you might be trying to convert a string to integer. but if you just want to check if the number is less than zero or not, you can do it in if statement. No need to throw an exception

网友答案:

Simplest way to to this is using an if statement

public void setId(String id) {
        Integer partnerId;
        try{
            partnerId = Integer.parseInt(id);
        } catch(Exception e){ /*if parsing fails do ...*/ }
        if (partnerId <= 0){ this.id = /*some default value*/ }
        else {this.id = id;}
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: