英文:
Is it a good practice/ non-expensive to call a method that doesn't throw exception inside try block in Java?
问题
以下是要翻译的代码部分:
原实现示例:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
//向 bos 写入数据
}
catch (Exception exception)
{
throw new exception
}
somemethod(bos, foo1, foo2);
修改后的示例:
try (ByteArrayOutputStream bos = new ByteArrayOutputStream())
{
//向 bos 写入数据
somemethod(bos, foo1, foo2);
}
catch (Exception exception)
{
throw new exception
}
需要将 somemethod
移到 try
块内,因为它需要使用 bos
变量。
英文:
for e.g. currently, I have this implementation:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
//write to bos
}
catch (Exception exception)
{
throw new exception
}
somemethod(bos, foo1, foo2);
}
Is it a good/bad practice/ inexpensive/expensive or makes any difference if I change this method to following:
try(ByteArrayOutputStream bos = new ByteArrayOutputStream())
{
//write to bos
somemethod(bos, foo1, foo2);
}
catch (Exception exception)
{
throw new exception
}
}
Had to move some method inside try as it needs bos variable.
答案1
得分: 4
Performance wise? Doesn't matter in the slightest.
Code-style-wise: That's a different story. You shouldn't toss methods into a try
block unless the associated catch and/or finally block are designed to deal with it. Instead, do this:
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. move the declaration outside. You can even do something like:
String foo; // no value assigned yet
try (someResource) {
foo = readFromIt; // assigned here though.
} catch (IOException e) {
throw a ResourceRetrievalException(e);
}
System.out.println(foo); // hey I'm using foo, outside the try!
NB: BAOS does not need a try block. If your linter is complaining about it, get a better linter. BAOS is not actually a resource that needs closing, the garbage collector will do the job.
英文:
Performance wise? Doesn't matter in the slightest.
Code-style-wise: That's a different story. You shouldn't toss methods into a try
block unless the associated catch and/or finally block are designed to deal with it. Instead, do this:
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. move the declaration outside. You can even do something like:
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!
NB: BAOS does not need a try block. If your linter is complaining about it, get a better linter. BAOS is not actually a resource that needs closing, the garbage collector will do the job.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论