根据 Cannot Create, Catch, or Throw Objects of Parameterized Types (Java Tutorials):
但是,您可以在
throws
子句中使用类型参数:class Parser<T extends Exception> { public void parse(File file) throws T { // OK // ... } }
但你为什么要这样做?你不能在这里构建T
。如果在外部构建之后注入T
,它的堆栈跟踪是不是全部错了?他们只是简单地记录了一个正常工作的功能,无论它有用吗?
答案 0 :(得分:3)
为什么不
class FooParser extends Parser<FooException> {
public void parse(File file) throws FooException {
throw new FooException("Not Supported");
}
}
答案 1 :(得分:1)
你可以
public class ExceptionWithPayload<T> extends Exception {
private final T payload;
public ExceptionWithPayload(T payload) {
this.payload = payload;
}
public T getPayload(){
return payload;
}
}
然后在其他课程中,你可以写
throw new ExceptionWithPayload<MyClass>(myObject);
以便能够将您喜欢的任何对象传递回捕获异常的事物,但是在catch
子句中进行类型检查。
答案 2 :(得分:1)
您可以将检查过的异常投掷到欺骗性投掷技巧所预期的位置:http://rdafbn.blogspot.hu/2013/07/lomboks-sneaky-throws.html
或者没有魔法:http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html