有时,为了避免使用 if
,我会创建抛出异常的代码来解析某些值。
例如:当您有一个输入字段可以在其中输入要搜索的合作伙伴编号或合作伙伴名称时,我确实喜欢:
try {
Integer.parseInt(string);
// use the input as int
} catch (NumberFormatException) {
// use the input as a String
}
现在我也遇到了类似的问题,但是使用的是InputStream
。
InputStream is;
try {
is = (FileInputStream) fileItem.getInputStream();
} catch (ClassCastException e) {
is = (ByteArrayInputStream) fileItem.getInputStream();
}
我的问题是:最好以这种方式抛出异常
或者可能是带有instanceof
的if,例如:
InputStream is;
if (fileItem.getInputStream() instanceof FileInputStream) {
is = (FileInputStream) fileItem.getInputStream();
} else if (fileItem.getInputStream() instanceof ByteArrayInputStream) {
is = (ByteArrayInputStream) fileItem.getInputStream();
}
还有为什么?
最佳答案
对于异常,更一般的规则是避免它们,如果它们也可以用更简单的结构(如 if)来表达。
生成异常的成本很高!它需要收集调用堆栈 - 并且取决于您的应用程序复杂性 - 仅此一项就可能成为堆上可怕的垃圾来源,需要由 GC 清理。
关于java - 生成异常或在 if 中使用 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28168231/