java try catch块的特殊语法

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); } 

我在The Java Tutorials上看到了这样一段代码,其中括号语句在关键字’try’之后。 这有效吗? 为什么不能eclipse识别它并报告语法错误?

这是Java 7的资源function尝试 。

您需要将Eclipse的编译器合规性级别设置为1.7才能识别语法。

您可以在Window > Preferences > Java > Compiler下全局设置它,也可以直接右键单击项目,如下所示:

在此处输入图像描述

Eclipse清楚地表明了为什么这不是有效的语法:

将项目编译器合规性设置设置为1.7

将项目JRE构建路径条目设置为“JavaSE-1.7”

这意味着,您已经安装了Java 6,但是教程

(…)主要描述Java SE 7中的function。

http://docs.oracle.com/javase/tutorial/index.html

这是Java 7中引入的try-with-resource语法.Eclise支持它,这就是它没有报告任何错误的原因:

日食

顺便说一句,您的代码也使用Java 7中引入的Files

不,它无效。 尝试这个:

 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); }