java 什么是Java中try catch中的圆括号/圆括号()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37583464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is Round brackets / parentheses () in try catch in Java
提问by Partha Sarathi Ghosh
As per as my knowledge we use try catch
as follows:
据我所知,我们使用try catch
如下:
try {
//Some code that may generate exception
}
catch(Exception ex) {
}
//handle exception
finally {
//close any open resources etc.
}
But in a code I found following
但是在我发现以下代码中
try(
ByteArrayOutputStream byteArrayStreamResponse = new ByteArrayOutputStream();
HSLFSlideShow pptSlideShow = new HSLFSlideShow(
new HSLFSlideShowImpl(
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(Constants.PPT_TEMPLATE_FILE_NAME)
));
){
}
catch (Exception ex) {
//handel exception
}
finally {
//close any open resource
}
I am not able to understand why this parentheses ()
just after try.
我无法理解为什么()
在尝试后使用这个括号。
What is the usage of it? Is it new in Java 1.7? What kind of syntax I can write there?
它的用途是什么?它是 Java 1.7 中的新功能吗?我可以在那里写什么样的语法?
Please also refer me some API documents.
还请给我参考一些 API 文档。
回答by Prasad Kharkar
It is try with Resources syntax which is new in java 1.7. It is used to declare all resources which can be closed. Here is the link to official documentation. https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
尝试使用 java 1.7 中的新资源语法。它用于声明所有可以关闭的资源。这是官方文档的链接。 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
在这个例子中,在 try-with-resources 语句中声明的资源是一个 BufferedReader。声明语句紧跟在 try 关键字之后的括号内。Java SE 7 及更高版本中的 BufferedReader 类实现了接口 java.lang.AutoCloseable。因为 BufferedReader 实例是在 try-with-resource 语句中声明的,所以无论 try 语句是正常完成还是突然完成(作为 BufferedReader.readLine 方法抛出 IOException 的结果),它都会关闭。