我有一小段Kotlin代码,实际上是在尝试忽略闭包内部的异常:
val remainderParts = arrayOf("/Company/Employees/Employee[Name='Michael", "Scott']/Salary", "45000")
var xpath: XPathExpression = (1..remainderParts.size).mapNotNull {
try {
XPathFactory.newInstance().newXPath().compile(remainderParts.subList(0, it).joinToString(" "))
}
catch (e: TransformerException) {
null
}
}.first()
但是,当代码运行时,无论如何TransformerException
都会被抛出该块。发生了什么事?
答案 0 :(得分:1)
您正在捕获错误的异常。您必须抓住public <T> List<T> readFromFile(String fileName) {
private String partialPath = "\\HW3\\src\\java\\repos\\";
try {
String path = partialPath + fileName;
FileInputStream fi = new FileInputStream(path);
ObjectInputStream oi = new ObjectInputStream(fi);
// Read objects
List<T> items = (List<T>) oi.readObject();
oi.close();
fi.close();
return items;
} catch (IOException | ClassNotFoundException e) {
}
}
:
XPathExpressionException
如果不确定,要捕获哪个异常,请使用val remainderParts = listOf("/Company/Employees/Employee[Name='Michael", "Scott']/Salary", "45000")
var xpath: XPathExpression = (1..remainderParts.size).mapNotNull {
try {
XPathFactory.newInstance().newXPath().compile(remainderParts.subList(0, it).joinToString(" "))
}
catch (e: XPathExpressionException) {
null
}
}.first()
(它是所有例外的基类)并输出如下类型:
Exception