我对java 8很陌生。
以下是我的代码,
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的方式合并/重构两次尝试捕获。
发布于 2016-06-13 08:53:08
你在找这个吗?
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
}发布于 2016-06-13 08:57:08
这取决于你所说的“合并”是什么意思。
如果您只是指有一个catch块,这很容易:只需将第二个try移动到第一个:
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块来完成。
发布于 2016-06-13 09:15:40
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();
}你可以这样用。
https://stackoverflow.com/questions/37785339
复制相似问题