如果使用 Long.parseLong() 解析失败,如何抛出异常?

How to throw an exception if parsing with Long.parseLong() fails?

我正在尝试编写某种堆栈计算器。

这是我处理 push 命令的代码的一部分。我只想推送整数,所以我必须摆脱任何无效的字符串,如 foobar (无法解析为整数)或 999999999999 (超出整数范围)。

strings 在我的代码中是 table 个字符串,其中包含 POPPUSH 等命令、数字和已经被白色字符分隔的随机杂乱。

主要问题:

我在为 long parseNumber = Long.parseLong(strings[i]); 抛出异常时遇到困难 - 我不知道如何处理这种情况,当 strings[i] 无法解析为 long 并且随后进入 integer.

while (i < strings.length) {
  try {
    if (strings[i].equals("PUSH")) {
      // PUSH 
      i++;
      if (strings[i].length() > 10)
        throw new OverflowException(strings[i]);
      // How to throw an exception when it is not possible to parse 
      // the string?
      long parseNumber = Long.parseLong(strings[i]); 
      
      if (parseNumber > Integer.MAX_VALUE)
        throw new OverflowException(strings[i]);
      
      if (parseNumber < Integer.MIN_VALUE)
        throw new UnderflowException(strings[i]);
      number = (int)parseNumber;
      stack.push(number);      
    }
    // Some options like POP, ADD, etc. are omitted here
    // because they are of little importance.
  }
  catch (InvalidInputException e)
    System.out.println(e.getMessage());
  catch (OverflowException e)
    System.out.println(e.getMessage());
  catch (UnderflowException e)
    System.out.println(e.getMessage());
  finally {
    i++;
    continue;
  }
}

不用担心。 Long.parseLong() 如果得到的不是 Number,则抛出 NumberFormatException

如果由于任何原因无法解析字符串,

Long.parseLong(String str) 将抛出 NumberFormatException。您可以通过为您的尝试添加一个 catch 块来捕获相同的内容,如下所示:

catch ( NumberFormatException e) {
    System.out.println(e.getMessage());
}

在阅读了您的评论和答案后,我想出了这样一个解决方案(此代码嵌入在外部 try-catch。)

if (strings[i].equals("PUSH")) {
  // PUSH 
  i++;
  if (strings[i].length() > 10) {
    throw new OverflowException(strings[i]);
  }

  try{
    parseNumber = Long.parseLong(strings[i]);

    if (parseNumber > Integer.MAX_VALUE) {
      throw new OverflowException(strings[i]);
    }

    if (parseNumber < Integer.MIN_VALUE) {
      throw new UnderflowException(strings[i]);
    }

    number = (int)parseNumber;
    stack.push(number);

  }
  catch (NumberFormatException n){
    throw new InvalidInputException(strings[i]);
  }                 
}