【问题标题】:Try and Catch on an int Array not working as expceted尝试捕获一个未按预期工作的 int 数组
【发布时间】:2019-02-26 16:18:12
【问题描述】:

我正在尝试对方法参数执行 try 和 catch,但我无法做到,并且当程序运行时,它给了我错误号格式错误,而不是在 catch 块中执行代码

感谢任何帮助。我是java和编程的初学者。感谢您花时间阅读我的问题。

 public void inputCheck(int[] checkUserInput) {
            try {
                if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {

                    errorMessage = "failEven";
                } else if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {

                    errorMessage = "failRange";

                } else if ((checkUserInput[0] >= 20 || checkUserInput[0] <= 80)
                        && (checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
                    errorMessage = "checkpassed";
                }

            } catch (NumberFormatException e){
                System.out.println("Please enter an number");
            }

        }

错误信息

 Exception in thread "main" java.lang.NumberFormatException: For input string: "e"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at java.lang.Integer.parseInt(Unknown Source)
        at UserInput.promptUser(UserInput.java:27)
        at MainClass.main(MainClass.java:11)
    #

【问题讨论】:

  • 请添加错误的stacktrace。
  • try-catch 中的代码似乎根本不会产生该异常。它不调用任何方法。所以异常会在别处抛出。密切注意堆栈跟踪中的行号。
  • 错误不在您发布的代码中。它在别的地方。
  • @Arnaud 异常在线程“main”java.lang.NumberFormatException:对于输入字符串:“e”在 java.lang.NumberFormatException.forInputString(未知来源)在 java.lang.Integer.parseInt( Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at UserInput.promptUser(UserInput.java:27) at MainClass.main(MainClass.java:11)
  • @displayName 我正在尝试检查用户是否将字符串输入到整数字段中,如果他们输入了我想显示错误消息

标签: java arrays try-catch numberformatexception


【解决方案1】:

您的代码不会引发任何类型的异常,因此根本不会执行 catch 块。

简单来说,try 块中的代码不会出现任何类型的运行时错误,因此根本不会到达 catch 块。只有当 try 块中的代码抛出异常时,才会执行 Catch 块。

【讨论】:

    【解决方案2】:

    仅当try 块中的代码产生这种类型的异常时,才会执行处理某种类型异常的catch 块。因此,只有当 try 块中的代码抛出 NumberFormatException 时,您的 catch 中的代码才能执行,但它不会。您必须要么在 try 块中显式抛出此类异常,要么调用可能抛出它的方法。

      try {
    
        if (someCondition) {
           throw new NumberFormatException();
        }
    
      } catch (NumberFormatException exp) {
          System.out.println("Invalid format" + e.getMessage());
      } 
    

    【讨论】:

      【解决方案3】:

      这里不需要 try 和 catch 块。此外,参数是 int 数组,您不能为参数传递字符串。 您可以使用下面的,将考虑第二个 ASCII 值。

      int arr[] = {100,'e'};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多