【问题标题】:Java program won't throw the desired exceptionJava 程序不会抛出所需的异常
【发布时间】:2016-08-12 08:05:41
【问题描述】:

我正在尝试用 Java 开发卡片验证程序。 isCardValid 方法主要检查给定卡号是否有效。我在那里指定了一个条件应该抛出一个IllegalArgumentException,但它没有&程序成功执行exit code 0

以下是我的 Java 文件:-

public class CardValidation {

  public static String getCardBrand(final String cardIsin){


        String brand = null;

        if (cardIsin == null || cardIsin.equals("")){
            log.warn("Given card BIN is null!! So returning null");
            return brand;
        }


        if (cardIsin.substring(0,2).matches("51|52|53|54|55"))
            brand = "MasterCard".toUpperCase();
        else if (cardIsin.startsWith("4"))
            brand = "Visa".toUpperCase();
        else if (cardIsin.startsWith("34") || cardIsin.startsWith("37"))
            brand = "Amex".toUpperCase();
        else if (Pattern.matches(maestroPattern,cardIsin))
            brand = "Maestro".toUpperCase();
        else if (Pattern.matches(diners, cardIsin))
            brand = "Diners".toUpperCase();
        else if (Pattern.matches(discover,cardIsin))
            brand = "Discover".toUpperCase();
        else if (doesFallInRupayRange(cardIsin))
            brand = "Rupay".toUpperCase();
        else if (cardIsin.startsWith("35"))
            brand = "JCB";

        return brand;
    }

  public static boolean isCardValid(final String cardNumber){

        if(cardNumber.matches("[^0-9]"))
            throw new IllegalArgumentException("INVALID ARGUMENT!!!! Card number should contain ONLY digits.");

        String cardBrand = getCardBrand(cardNumber);

        if (cardBrand == null)
            return false;
        if(cardBrand.equalsIgnoreCase("VISA") || cardBrand.equalsIgnoreCase("MasterCard") ||
                cardBrand.equalsIgnoreCase("DISCOVER") || cardBrand.equalsIgnoreCase("RUPAY")) {
            return cardNumber.length() == 16;
        }
        else if(cardBrand.equalsIgnoreCase("AMEX")) {
            return cardNumber.length() == 15;
        }
        else if(cardBrand.equalsIgnoreCase("MAESTRO")) {
            return cardNumber.length() == 16 || cardNumber.length() == 19;
        }
        else if(cardBrand.equalsIgnoreCase("DINERS")) {
            return cardNumber.length() == 14;
        }
        log.info("Unknown card number brand: " + cardNumber);
        return cardNumber.length() >= 12;
    }

public static boolean doesFallInRupayRange(final String isin){

       long intIsin = Long.parseLong(isin.replaceAll("[^\\d]", "").substring(0,6));

        for (int row = 0; row < CardValidation.rupayRange.length; row++)
        {
            try {
                if (intIsin >= CardValidation.rupayRange[row][0] && intIsin <= CardValidation.rupayRange[row][1])
                    return true;
            }
            catch (Exception e) {
                log.error("Error while checking for RuPay: " + isin, e);
            }
        }
        return false;
    }

    public static void main (String... args){
        CardValidation.isCardValid("42424242hghghghgh");
    }
}

现在下面的代码 sn-p 应该抛出提到的Exception,不是吗,因为我故意从我的 ma​​in 中为方法提供无效参数?

 if(cardNumber.matches("[^0-9]"))
            throw new IllegalArgumentException("INVALID ARGUMENT!!!! Card number should contain ONLY digits.");

以下是我在控制台中得到的输出

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

Process finished with exit code 0

【问题讨论】:

    标签: java exception exception-handling illegalargumentexception throw


    【解决方案1】:

    您的正则表达式错误

    试试这个:

    String regex = "\d+";
    

    或者:

    String regex = "[0-9]+";
    

    因此无效号码不匹配;所以也不例外。

    为了使用上述模式,你必须反转逻辑:

    if ( ! input.matches(regex) ) {
      throw exception
    

    但请注意:您的代码“不好”。例如:您没有使用任何类型的抽象。您将信用卡类型表示为 Strings。这就像超级糟糕。因为处理不同信用卡的每段代码......都必须知道“AMEX”的意思是“美国快递;等等。考虑使用 Enum 代替。

    换句话说:您真的很想阅读/了解如何做好面向对象的设计!

    【讨论】:

    • 我在这里要做的是,检查cardNumberString 是否包含除数字以外的任何内容。给定的表达式 [^0-9] 不应该工作吗?并感谢您的建议,我将它们更改为枚举
    • 这就是我要告诉你的:如果输入仅包含数字,我的模式 匹配。你的没有。只需研究正则表达式的规则即可了解原因!
    • @Auro 玩和学习正则表达式的好方法是RegExr
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2015-02-13
    • 2018-09-18
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多