我有这样的情况
String str = null;
try{
...
str = "condition2";
}catch (ApplicationException ae) {
str = "condition3";
}catch (IllegalStateException ise) {
str = "condition3";
}catch (Exception e) {
str = "condition3";
}
if(str == null){
str = "none";
}
现在我想将所有 str = "condition3";
总结在一行中。由于finally block 总是运行,所以这不能满足我的需求。还能做什么。
最佳答案
从 Java 7 开始,您可以 catch multiple exception types在单个 catch
block 中。代码看起来像这样:
String str = null;
try {
...
str = "condition2";
} catch (ApplicationException|IllegalStateException|Exception ex) {
str = "condition3";
}
顺便说一句:您发布的代码以及我的 Java 7 代码都可以简单地折叠为 catch (Exception e)
,因为 Exception
是 ApplicationException
的父类(super class)和 IllegalStateException
.
关于java - 最后阻止以不同的方式表现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10793443/