简体   繁体   English

Java try-with-resources 语句在编译时被重新报告为错误

[英]Java try-with-resources statements were reproted as error at compile time

An example from the book Core Java Volume II Advanced Features used try-with-resources statements for a simple echo server program. Core Java Volume II Advanced Features一书中的一个示例使用了 try-with-resources 语句用于简单的 echo 服务器程序。 However, when I compiled the program, the compiler reported errors shown after the code for the program below.但是,当我编译程序时,编译器报告了下面程序代码后显示的错误。 Thank you for your help.谢谢您的帮助。

Code for the program:程序代码:

 /**
 * 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;
                    }
                }
            }
        }
    }
 }

Error messages reported by compiler:编译器报告的错误信息:

在此处输入图像描述

It is as the error says.正如错误所说。

The try-with-resources is auto-closing the resources you declare in the try(...) at the end of the block but it doesn't handle automatically exceptions for you. try-with-resources 会自动关闭您在块末尾的try(...)中声明的资源,但它不会自动为您处理异常。

So you either need to:所以你要么需要:

  1. Write catch block to handle IOException s编写catch块来处理IOException s
  2. Declare that the method ( main ) throws those exceptions.声明方法 ( main ) 抛出这些异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM