新/奇怪的Java" try()"句法? [英] New/strange Java "try()" syntax?
问题描述
在使用Eclipse中的自定义格式选项时,在其中一个示例代码中,我看到了如下代码:
While messing around with the custom formatting options in Eclipse, in one of the sample pieces of code, I saw code as follows:
/**
* 'try-with-resources'
*/
class Example {
void foo() {
try (FileReader reader1 = new FileReader("file1"); FileReader reader2 = new FileReader("file2")) {
}
}
}
我从未见过尝试
这样使用我已经用Java编写了9年!有人知道你为什么要这样做吗?这样做有什么用例/好处?
I've never seen try
used like this and I've been coding in Java for 9 years! Does any one know why you would do this? What is a possible use-case / benefit of doing this?
我看到的其他代码片段,我认为这是一个非常有用的简写,所以我在这里分享它同样,它的作用非常明显:
An other pieces of code I saw, I thought was a very useful shorthand so I'm sharing it here as well, it's pretty obvious what it does:
/**
* 'multi-catch'
*/
class Example {
void foo() {
try {
} catch (IllegalArgumentException | NullPointerException | ClassCastException e) {
e.printStackTrace();
}
}
}
推荐答案
它是在Java 7中添加的。它被称为 try-with-resources 声明。
It was added in Java 7. It's called the try-with-resources statement.
/编辑
不妨把它放在这里。如果你使用这样的包装类,你可以使用try-with-resources语句来管理 Lock
:
Might as well throw this in here too. You can use the try-with-resources statement to manage Lock
s if you use a wrapper class like this:
public class CloseableLock implements Closeable {
private final Lock lock;
private CloseableLock(Lock l) {
lock = l;
}
public void close() {
lock.unlock();
}
public static CloseableLock lock(Lock l) {
l.lock();
return new CloseableLock(l);
}
}
try(CloseableLock l = CloseableLock.lock(lock)) { // acquire the lock
// do something
} // release the lock
但是,由于你必须为每个资源声明一个变量,这个优点是是值得商榷的。
However, since you have to declare a variable for every resource, the advantage of this is debatable.
这篇关于新/奇怪的Java" try()"句法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!