Rollerball
Rollerball

Reputation: 13118

Inquiry about try-with-resources statement

Just confirming that the following does not compile and it's not a mistake of mine:

try(Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
        {
        }
        catch(IOException io){io.printStackTrace();}

However the following compiles:

try(BufferedWriter bw =Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())
        {
        }
        catch(IOException io){io.printStackTrace();}

It seems that the compiler check whether or not the classes declared in the try-catch-with-resources statement implement AutoClosable... however It could have worked since the method returns a BufferedWriter which implements AutoClosable.

Just asking for a confirmation that

try(Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt"), Charset.defaultCharset())

does not compile.

Thanks in advance.

Upvotes: 1

Views: 79

Answers (2)

mthmulders
mthmulders

Reputation: 9705

The Java tutorial states:

The try-with-resources statement is a try statement that declares one or more resources.

In your first snippet, you don't declare a resource:

Files.newBufferedWriter(Paths.get("/home/user/Desktop/TryItOutMan.txt")

Whilst in your second snippet, you do:

BufferedWriter bw = ....

Upvotes: 2

assylias
assylias

Reputation: 328873

If you look at the syntax definition of the try-with-resources in the JLS, you will see that it expects a variable name. So it must look like:

try (SomeType variable = xxx;)

Upvotes: 5

Related Questions