java - 为什么在这段代码(IDE Eclipse)中没有抛出 EOFException?
问题描述
我有以下代码,Eclipse 在 catch 块中报告 EOFException 永远不会在 try 块中抛出。
我试图把这两行:
String suit = null;
String rank = null;
在 try 块中,catch 块的错误消失了。
我也试着把这两行:
char s = suitString2Char(suit);
char r = rankString2Char(rank);
在 try 块中,catch 块的错误消失了。
但是当我把整个代码体放在 try 块中时,同样的错误又发生了。
public static Card read2(BufferedReader in) throws EOFException {
Scanner input = new Scanner(in);
String suit = null;
String rank = null;
try {
int i = 0;
while (input.hasNext()) {
suit = i == 0 ? input.next() : suit;
rank = i == 1 ? input.next() : rank;
i++;
}
input.close();
} catch (EOFException e) {
throw new EOFException();
}
char s = suitString2Char(suit);
char r = rankString2Char(rank);
if (isValidSuit(s)
&& isValidRank(r)) {
return new Card(s, r);
} else {
return null;
}
}
解决方案
首先: 错误消失了,因为当您进行建议的编辑时,您创建的代码无法编译。
第二:
Scanner.next()
不会抛出 EOFexception。它抛出
@throws NoSuchElementException if no more tokens are available
@throws IllegalStateException if this scanner is closed
which 是RuntimeException
s 而不是EOFException
which 是所谓的“检查异常”。
当抱怨错误时,编译器会以不同的方式处理它们。
如果检查的异常可以通过方法或构造函数的执行抛出并传播到方法或构造函数边界之外,则需要在方法或构造函数的 throws 子句中声明它们。
RuntimeException及其子类是未经检查的异常。如果未经检查的异常可以通过方法或构造函数的执行抛出并传播到方法或构造函数边界之外,则不需要在方法或构造函数的 throws 子句中声明它们。
推荐阅读
- azure-devops - 对 Azure DevOps Server 使用自定义工作
- jenkins - 如何使用 Jenkins 将 BitBucket webhook 帖子内容存储到文件中?
- bash - 如何在bash中逃避反引号
- python - 如何在 discord.py 最新版本中分配角色?
- c - 我在 c 中有一个损坏的 while 循环
- javascript - EJS 文件作为静态 HTML 而不是 JS 打开
- javascript - 如何从http请求NodeJS中获取变量?
- google-cloud-platform - 将 GCP 访问的 IP 列入白名单
- java - 如何制作一个正则表达式来匹配以 0-9 或 az 开头的带有重音符号的字符串,并且必须只接受这个特殊字符 - 单词之间的 _ '?
- reactjs - react native和flutter最大的区别是什么?