当try尝试成功时如何修复catch语句

问题描述 投票:-1回答:1

您好我刚刚开始学习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语句。先感谢您。

java try-catch
1个回答
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)并使用long。

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;

}

, 最好的祝福。

© www.soinside.com 2019 - 2024. All rights reserved.