问题
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
I saw such a piece of code on The Java Tutorials, in which a bracket statement is after key word 'try'. Is this valid? why cannot eclipse recognize it and report syntax error?
回答1:
It is the Java 7's try with resource feature.
You need to set Eclipse's Compiler Compliance level to 1.7 for it to recognize the syntax.
You can either set it globally under Window > Preferences > Java > Compiler
or simply right-click on the project and do as shown below:

回答2:
Eclipse clearly indicates why this is not valid syntax:
Set project compiler compliance settings to 1.7
Set project JRE build path entry to 'JavaSE-1.7'
That means, you have Java 6 installed, but the tutorials
(...) primarily describe features in Java SE 7.
http://docs.oracle.com/javase/tutorial/index.html
回答3:
This is a try-with-resource syntax introduced in Java 7. It is supported by Eclise, that's why it is not reporting any error:

BTW your code also uses Files introduced in Java 7.
回答4:
No, it's not valid. Try this:
Charset charset = Charset.forName("US-ASCII");
try {
BufferedReader reader = Files.newBufferedReader(file, charset);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
来源:https://stackoverflow.com/questions/9582053/special-syntax-of-java-try-catch-block