首页 > 解决方案 > 为什么在这段代码(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;
    }
}

标签: javaexception

解决方案


首先: 错误消失了,因为当您进行建议的编辑时,您创建的代码无法编译。

第二:

Scanner.next()不会抛出 EOFexception。它抛出

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

which 是RuntimeExceptions 而不是EOFExceptionwhich 是所谓的“检查异常”。

当抱怨错误时,编译器会以不同的方式处理它们。

如果检查的异常可以通过方法或构造函数的执行抛出并传播到方法或构造函数边界之外,则需要在方法或构造函数的 throws 子句中声明它们。

RuntimeException及其子类是未经检查的异常。如果未经检查的异常可以通过方法或构造函数的执行抛出并传播到方法或构造函数边界之外,则不需要在方法或构造函数的 throws 子句中声明它们。


推荐阅读