【发布时间】:2015-04-29 20:24:28
【问题描述】:
我正在尝试编写某种堆栈计算器。
这是我处理push 命令的代码的一部分。我只想推送整数,所以我必须删除任何无效的字符串,如foobar(无法解析为整数)或999999999999(超出整数范围)。
我的代码中的strings 是一个字符串表,其中包含POP 或PUSH 等命令、数字和已被白色字符分割的随机杂波。
主要问题:
我在为 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;
}
}
【问题讨论】:
-
NumberFormatException -
Long.parseLong 如果无法解析字符串,则抛出 NumberFormatException。您可以将其包装在 try-catch 中以捕获字符串不长的情况。
-
@nullPointer,好的,所以我的想法是,如果我想为练习添加自己的异常,我可以为
long parseNumber = Long.parseLong(strings[i]);再做一次 try-catch,对吧? -
@Mateusz 是正确的
标签: java exception-handling try-catch