Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my usage of nested try-with-resource correct?

Tags:

java

I have simple TCP server which prints the message sent by client. I'm trying to modify it to use try-with-resource feature. Is using nested try-with-resource statement in my example correct?

public static void main(String args[]) throws IOException {
    String receivedMessage;

    try (ServerSocket serverSocket = new ServerSocket(777)) {
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("Client connected");
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                while ((receivedMessage = in.readLine()) != null) {
                    System.out.println(receivedMessage);
                }
                System.out.println("Client disconnected");
            }
        }
    }
}

}

like image 502
Daniil Molchanov Avatar asked Jan 17 '15 07:01

Daniil Molchanov


People also ask

Is it okay to have nested try catch?

Nesting try-catch blocks severely impacts the readability of source code because it makes it to difficult to understand which block will catch which exception.

Which of the following is the correct syntax of try with resources?

The try-with-resources statement automatically closes all the resources at the end of the statement. A resource is an object to be closed at the end of the program. As seen from the above syntax, we declare the try-with-resources statement by, declaring and instantiating the resource within the try clause.

What is the difference between try and try with resources?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement.

Can we use finally with try with resources?

You can use catch and finally blocks with try-with-resources statement just like an ordinary try statement.


1 Answers

Yes, your example is correct.

A try-with-resources try block can stand alone because it has an implicit finally block; whereas a traditional try block is required to be followed by a catch block and/or a finally block.

Thus your example code is equivalent to the following (besides the resource variables being visible outside the scope of their respective try blocks):

        final ServerSocket serverSocket = new ServerSocket(777);
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected");
                final BufferedReader in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                try {
                    while ((receivedMessage = in.readLine()) != null) {
                        System.out.println(receivedMessage);
                    }
                    System.out.println("Client disconnected");
                } finally {
                    in.close();
                }
            }
        } finally {
            serverSocket.close();
        }

I would have recommended you put both resources inside the same try block, except in your case that doesn't work because it's necessary to call accept() on the serverSocket before asking for its inputStream().

However, there's still an appropriate opportunity in your code example to put multiple resources in your second try-with-resources:

try (Reader stream = new InputStreamReader(socket.getInputStream());
     BufferedReader in = new BufferedReader(stream)) {
  // do stuff, still preferring to use 'in' here rather than 'stream'
}
like image 113
gknicker Avatar answered Oct 26 '22 20:10

gknicker