首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在java 8中合并尝试捕获

在java 8中合并尝试捕获
EN

Stack Overflow用户
提问于 2016-06-13 08:48:06
回答 3查看 516关注 0票数 0

我对java 8很陌生。

以下是我的代码,

代码语言:javascript
复制
File file = new File("C:\\abc\\def\\ghi"); //def, ghi doesnot exists
file.mkdirs();
try {
    file.createNewFile(); //throw IOE
} catch (IOE ioe) {
}  
try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));) {
       //some logic
} catch (IOE ioe) {
}

如何以java 8的方式合并/重构两次尝试捕获。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-06-13 08:53:08

你在找这个吗?

代码语言:javascript
复制
File file = new File("C:\\abc\\def\\ghi"); //def, ghi doesnot exists
file.mkdirs();
try {
    file.createNewFile(); //throw IOE
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file)));
       //some logic
} catch (IOE ioe) {
       // handleException
}
票数 1
EN

Stack Overflow用户

发布于 2016-06-13 08:57:08

这取决于你所说的“合并”是什么意思。

如果您只是指有一个catch块,这很容易:只需将第二个try移动到第一个:

代码语言:javascript
复制
File file = new File("C:\\abc\\def\\ghi"); //def, ghi doesnot exists
file.mkdirs();
try {
    file.createNewFile(); //throw IOE
    try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file))) {
       //some logic
    }
} catch (IOE ioe) {
    // Common handling of IOE.
}

我不打算进一步合并它;第二个/内部try具有关闭流的语义。这是一件好事,需要一个try块来完成。

票数 2
EN

Stack Overflow用户

发布于 2016-06-13 09:15:40

代码语言:javascript
复制
File file = new File("C:\\abc\\def\\ghi"); //def, ghi doesnot exists
file.mkdirs();
BufferedOutputStream stream = null;
try {
     file.createNewFile(); //throw IOE
     stream = new BufferedOutputStream(new FileOutputStream(file));
                   //some logic
} catch (IOException ioe) {
                // handleException
} finally {
       if (stream != null)
       stream.close();
}

你可以这样用。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37785339

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档