Java 有没有办法在另一个try-catch-finally块中简化try-catch块?
我是Java新手,正在尝试学习捕获异常的概念。我在网上看到了这段代码,在另一个try-catch-finally块的主体中有一个try-catch块。我只是想知道是否有任何方法可以简化代码,以便以更清晰的方式编写Java 有没有办法在另一个try-catch-finally块中简化try-catch块?,java,exception,exception-handling,try-catch,Java,Exception,Exception Handling,Try Catch,我是Java新手,正在尝试学习捕获异常的概念。我在网上看到了这段代码,在另一个try-catch-finally块的主体中有一个try-catch块。我只是想知道是否有任何方法可以简化代码,以便以更清晰的方式编写 public static void main(String[] args) { Properties p1 = new Properties(); OutputStream os1 = null; try { os1 = new FileOu
public static void main(String[] args) {
Properties p1 = new Properties();
OutputStream os1 = null;
try {
os1 = new FileOutputStream("xanadu123.properties");
//set the properties value
p1.setProperty("database", "localhost");
p1.setProperty("1", "one");
p1.setProperty("2", "two");
p1.store(os1, "this is the comment");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os1 != null) {
try {
os1.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
这确实是一种非常常见的模式,因此最近Java中添加了一种特殊的语法: 你能行
try(OutputStream os1 = new FileOutputStream("xanadu123.properties")){
}
catch (WhatYouHadBefore e){}
// no more finally, unless you want it for something else
这将被
最终
自动关闭(即使没有最终
块),关闭过程中的任何错误都将被抑制。根据javadocs,在JavaSE7及更高版本中,您可以使用,并在完成后自动关闭资源
public static void main(String[] args) {
Properties p1 = new Properties();
OutputStream os1 = null;
try(os1 = new FileOutputStream("xanadu123.properties")){ //set the properties value
p1.setProperty("database", "localhost");
p1.setProperty("1", "one");
p1.setProperty("2", "two");
p1.store(os1, "this is the comment");
} catch (IOException e) {
e.printStackTrace();
}
}