尝试成功时执行catch语句如何解决

时间:2018-09-05 21:58:32

标签: java try-catch

你好,我刚刚开始学习Java,我在一个项目中遇到了这个问题。 我的try.catch语句用于检查新电话号码是否仅包含数字并且长度为10个字符。

public void setBusinessPhone(String newBusinessPhone) {
    int numberTest;//Used to test if the new number contains any non digit characters.

    if (newBusinessPhone.length() != 10) { //test to see if the phone number is 10 characters in length.
        throw new IllegalArgumentException("Phone number must be 10 digits in length.");
    }

    try { //Test if the new phone number contains any non numeric characters.
        numberTest = Integer.parseInt(newBusinessPhone);
    }
    catch ( NumberFormatException e) { //Number contains invalid characters print an error message to the user.
        System.out.println("Not a legal phone number. Please enter a phone number 10 digits in length and only contains digits 0-9.");
    }
    businessPhone = newBusinessPhone;

}

当try语句成功执行时,catch语句仍将执行。我如何让代码仅在try语句遇到异常时才执行catch语句。预先谢谢你。

1 个答案:

答案 0 :(得分:1)

在Java api中,Integer.parseInt(newBusinessPhone)调用此方法

  public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
  }

在parseInt(s,10)中,其中var s是您的newBusinessPhone,api表示该数字不能大于2147483647示例parseInt(“ 2147483648”,10)引发NumberFormatException,解决方案使用Long.parseUnsignedLong(newBusinessPhone)并使用长。

public void setBusinessPhone(String newBusinessPhone) {
    long numberTest;//Used to test if the new number contains any non digit characters.

    if (newBusinessPhone.length() != 10) { //test to see if the phone number is 10 characters in length.
        throw new IllegalArgumentException("Phone number must be 10 digits in length.");
    }

    try { //Test if the new phone number contains any non numeric characters.
        numberTest = Long.parseUnsignedLong(newBusinessPhone);
    }
    catch ( NumberFormatException e) { //Number contains invalid characters print an error message to the user.
        System.out.println("Not a legal phone number. Please enter a phone number 10 digits in length and only contains digits 0-9.");
    }
    businessPhone = newBusinessPhone;

}

,最好的问候。