gpt4 book ai didi

java - 为什么这段代码(IDE Eclipse)中没有抛出 EOFException?

转载 作者:行者123 更新时间:2023-11-30 05:50:24 25 4
gpt4 key购买 nike

我有以下代码,Eclipse 在 catch block 中报告说 EOFException 永远不会在 try block 中抛出。

我试图把这两行:

String suit = null;
String rank = null;

在try block 中,catch block 处的错误消失了。

我还尝试添加这两行:

char s = suitString2Char(suit);
char r = rankString2Char(rank);

在try block 中,catch block 处的错误消失了。

但是当我将整个代码体放入 try block 时,同样的错误再次发生。

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()不会抛出 EOF 异常。它抛出

@throws NoSuchElementException if no more tokens are available
@throws IllegalStateException if this scanner is closed

分别是 RuntimeException s 而不是 EOFException这就是所谓的“检查异常”。

编译器在提示错误时会以不同的方式处理它们。

Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

关于java - 为什么这段代码(IDE Eclipse)中没有抛出 EOFException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com