首页 文章

扫描程序返回null而不是抛出异常

提问于
浏览
1

我在java中使用网络时遇到了麻烦 . 我试图通过套接字从客户端读取消息 . 我使用BufferedReader来读取消息 .

public String read() throws IOException {
    String message = reader.readLine();
    return message;
}

当我在服务器上的reader.readline()方法时,如果客户端终止连接,我实际上会发生错误 . 但是,它不是抛出异常,而是返回NULL .

2 回答

  • 1

    @Eray Tuncer它取决于连接何时关闭,如果它是在开始读取行之前,那么是的,你应该期待一个例外 . 但如果介于两者之间,我认为你会得到“null”表示流的结束 . 请从BufferedReader检查以下readLine实现:

    String readLine(boolean ignoreLF)throws IOException {StringBuffer s = null; int startChar;

    synchronized (lock) {
            ensureOpen(); //This method ensures that the stream is open and this is called before start reading
    

    .................. ................ // ----如果连接关闭,则开始读取操作将只返回一个null --------- bufferLoop:for(;;){

    if (nextChar >= nChars)
                    fill();
                if (nextChar >= nChars) { /* EOF */
                    if (s != null && s.length() > 0)
                        return s.toString();
                    else
                        return null;
                }
                boolean eol = false;
                char c = 0;
                int i;
    
                /* Skip a leftover '\n', if necessary */
                if (omitLF && (cb[nextChar] == '\n'))
                    nextChar++;
                skipLF = false;
                omitLF = false;
    
            charLoop:
                for (i = nextChar; i < nChars; i++) {
                    c = cb[i];
                    if ((c == '\n') || (c == '\r')) {
                        eol = true;
                        break charLoop;
                    }
                }
    
                startChar = nextChar;
                nextChar = i;
    
                if (eol) {
                    String str;
                    if (s == null) {
                        str = new String(cb, startChar, i - startChar);
                    } else {
                        s.append(cb, startChar, i - startChar);
                        str = s.toString();
                    }
                    nextChar++;
                    if (c == '\r') {
                        skipLF = true;
                    }
                    return str;
                }
    
                if (s == null)
                    s = new StringBuffer(defaultExpectedLineLength);
                s.append(cb, startChar, i - startChar);
            }
        }
    }
    

    所以底线是你应该在这个操作中检查null,而不是依赖于IOException . 我希望它能帮助你解决问题 . 谢谢 !

  • 0

    您可以手动触发异常,如下所示:

    public String read() throws IOException {
        String message = reader.readLine();
        if (message == null)
            throw new IOException("reader.readLine() returned null");
        return message;
    }
    

相关问题