M.S*_*idu 7 java exception try-catch numberformatexception multi-catch
我真的想使用Java-1.7的功能.其中一个功能是"Multi-Catch".目前我有以下代码
try {
int Id = Integer.parseInt(idstr);
TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));
updateTotalCount(tempTypeInfo);
} catch (NumberFormatException numExcp) {
numExcp.printStackTrace();
} catch (Exception exception) {
exception.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我想从上面的代码中删除两个catch块,而是使用如下所示的单个catch:
try {
int Id = Integer.parseInt(idstr);
TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));
updateTotalCount(tempTypeInfo);
} catch (Exception | NumberFormatException ex) { // --> compile time error
ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
但上面的代码给出了编译时错误:
"NumberFormatException"已被替代Exception捕获.
我理解上面的编译时错误但是我的第一个代码块的替换是什么.
Mur*_*nik 10
NumberFormatException是.的子类Exception.说这两个catch块应该具有相同的行为就像是说你没有任何特殊的治疗方法NumberFormatException,只是你所拥有的一般治疗方法Exception.在这种情况下,您可以只省略其catch块catch Exception:
try {
int Id = Integer.parseInt(idstr);
TypeInfo tempTypeInfo = getTypeInfo(String.valueOf(Id));
updateTotalCount(tempTypeInfo);
} catch (Exception exception) {
exception.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3912 次 |
| 最近记录: |