【问题标题】:Java try-with-resources statements were reproted as error at compile timeJava try-with-resources 语句在编译时被重新报告为错误
【发布时间】:2020-06-03 23:26:21
【问题描述】:

Core Java Volume II Advanced Features一书中的一个例子使用了 try-with-resources 语句来实现一个简单的 echo 服务器程序。但是,当我编译程序时,编译器报告了下面程序代码后显示的错误。感谢您的帮助。

程序代码:

 /**
 * Listing 3.3 server/EchoServer.java
 */
 package server;

 import java.io.*;
 import java.net.*;
 import java.util.*;

 /**
  * This pgoram implements a simple server
  * that listens to port 8189 and echoes
  *  back all client input.
  * @version 1.21 2012-05-19
  * @author Cay Horstmann
  */
 public class EchoServer {
    public static void main(String[] args) {
        // establish server socket
        try (ServerSocket s = new ServerSocket(8189)) {
            // wait for client connection
            try (Socket incoming = s.accept()) {
                InputStream inStream = incoming.getInputStream();
                OutputStream outStream = incoming.getOutputStream();
                try (Scanner in = new Scanner(inStream)) {
                    PrintWriter out = new PrintWriter(outStream, true /*autoFlush*/);
                    out.println("Heloo! Enter BYE to exit");
                    // echo client input
                    boolean done = false;
                    while (!done && in.hasNext()) {
                        String line = in.nextLine();
                        out.println("Echo: " + line);
                        if (line.trim().toUpperCase().equals("BYE"))
                            done = true;
                    }
                }
            }
        }
    }
 }

编译器报告的错误信息:

【问题讨论】:

    标签: java try-with-resources


    【解决方案1】:

    正如错误所说。

    try-with-resources 会自动关闭您在块末尾的 try(...) 中声明的资源,但它不会自动为您处理异常。

    所以你要么需要:

    1. catch块来处理IOExceptions
    2. 声明方法 (main) 会引发这些异常。

    【讨论】:

    • 谢谢你,@KrzyszlofMazur。这是正确的。我应该在 main 方法中附加一个 throws IOException。
    猜你喜欢
    • 2018-10-20
    • 1970-01-01
    • 2014-05-21
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多