【发布时间】:2018-05-20 23:25:09
【问题描述】:
我有这样的方法。
@Override
public Optional<List<Order>> getPendingOrders(AuthDTO authDTO) throws MyException {
return connector.getConnection(authDTO).map(p->p.getOrders());
}
这里
connector.getConnection(authDTO)
返回一个可选的连接和
p->p.getOrders()
抛出我无法更改的 KException,其形式为
public class KException extends Throwable {
// variables
public String message;
public int code;
// constructor that sets the message
public KException(String message){
this.message = message;
}
// constructor that sets the message and code
public KException(String message, int code){
this.message = message;
this.code = code;
}
}
这就是 MyException 的结构
public class MyException extends KException {
public MyException(String message, int code) {
super(message, code);
}
}
代码未编译并出现以下错误
unreported exception com.something.exceptions.KException; must be caught or declared to be thrown
我想将此 KException 转换为 MyException。有没有一种优雅的方式来做到这一点?请帮忙。
【问题讨论】:
-
你为什么不扔
KException? -
只有扩展 MyException 才能转换它。
-
...你不能扩展
KException? -
将你的
return语句包装在try-catch中,然后扔掉你需要的任何东西。 -
返回一个空的
Optional<List<Order>>是什么意思?真的会和空的List<Order>有不同的含义吗?您应该避免将集合包装到可选项中(反之亦然),因为这对于调用者来说非常麻烦。