2
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

4 Answers 4

2

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:

enter image description here

3
  • The OP says: "why cannot eclipse recognize it and report syntax error?" - his Eclipse recognizes this syntax, it already works with 1.7 JDK... Mar 6, 2012 at 10:53
  • Further Question:I installed JRE1.7 into Eclipse(by Windows-Preference-Java-Installed JRE) and was able to import related packages. But I cannot find 1.7 in Executation Env, and also cannot set Complier compliance level as 1.7. WHY?
    – user796857
    Mar 7, 2012 at 7:08
  • @user796857 Because what you need is the JDK, not the JRE.
    – adarshr
    Mar 7, 2012 at 9:08
1

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

1

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:

Eclipse

BTW your code also uses Files introduced in Java 7.

0

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);
}
2
  • 1
    This question is not tagged "java 7", so this answer is correct given the (reasonable) assumption that we're in java 6 land
    – Bohemian
    Mar 6, 2012 at 11:17
  • Agree, but it looks like the OP simply wasn't aware of Java 7 existence and features. BTW Java 6 end of life is scheduled for this November: oracle.com/technetwork/java/eol-135779.html Mar 6, 2012 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.