Special syntax of java try catch block

自闭症网瘾萝莉.ら 提交于 2019-12-10 10:38:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!