问题描述
例如目前,我有此实现:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
//write to bos
}
catch (Exception exception)
{
throw new exception
}
somemethod(bos,foo1,foo2);
}
如果将这种方法更改为以下方法,它是一种好的/不好的做法/便宜的/昂贵的还是有所作为?
try(ByteArrayOutputStream bos = new ByteArrayOutputStream())
{
//write to bos
somemethod(bos,foo2);
}
catch (Exception exception)
{
throw new exception
}
}
由于需要bos变量,因此不得不在try中移动某些方法。
解决方法
明智的表现?没关系。
明智的代码风格:这是另一回事。除非相关的catch和/或finally块旨在处理该方法,否则不应将方法扔到try
块中。相反,请执行以下操作:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
// write to bos
} catch (Exception e) {
// handle things - you really want to catch ALL exceptions?
}
somemethod(bos,foo1,foo2);
即将声明移到外面。您甚至可以执行以下操作:
String foo; // no value assigned yet
try (someResource) {
foo = readFromIt; // assigned here though.
} catch (IOException e) {
throw new ResourceRetrievalException(e);
}
System.out.println(foo); // hey I'm using foo,outside the try!
注意:BAOS不需要try块。如果您的短毛绒抱怨,请得到更好的短毛绒。 BAOS实际上不是需要关闭的资源,垃圾收集器将完成此工作。