调用一个不';在Java中,try块内不会抛出异常?
例如,目前,我有以下实施:调用一个不';在Java中,try块内不会抛出异常?,java,try-catch,Java,Try Catch,例如,目前,我有以下实施: ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { //write to bos } catch (Exception exception) { throw new exception } somemethod(bos,
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, foo1, foo2);
}
catch (Exception exception)
{
throw new exception
}
}
必须在内部移动一些方法,因为它需要bos变量。性能方面?一点也不重要 代码风格方面:这是一个不同的故事。除非相关的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);
i、 e.将声明移到外面。您甚至可以执行以下操作:
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块。如果你的皮棉有问题,找一个更好的皮棉。BAO实际上不是一个需要关闭的资源,垃圾收集器将完成这项工作