[英]Replace a checked exception with a runtime exception?
Given that I basically want to eliminate checked exception usage and transform them to runtime exceptions, I would normally be doing something like this: 鉴于我基本上想要消除已检查的异常使用并将它们转换为运行时异常,我通常会做这样的事情:
try {
file.read();
} catch (IOException e){
throw new RuntimeException(e);
}
There are several disadvantages to doing this, but the one that irritates me the most is that my runtime exception would contain a nested stacktrace. 这样做有几个缺点,但最让我恼火的是我的运行时异常将包含嵌套的堆栈跟踪。 Basically I would like to re-throw the "IOException" as a RuntimeException (or "IORuntimeException") with the original message and stacktrace, so I can avoid the useless nested stacktrace.
基本上我想将“IOException”作为RuntimeException(或“IORuntimeException”)重新抛出原始消息和stacktrace,这样我就可以避免无用的嵌套堆栈跟踪。 The "fact" that I have re-thrown the exception somewhere in the middle seems like just useless noise to me.
我在中间某处重新抛出异常的“事实”对我来说似乎只是无用的噪音。
Is this possible ? 这可能吗 ? Is there any library that does this ?
有没有这样做的图书馆?
Project Lombok允许您完全禁用已检查的例外。
class IORuntimeException extends RuntimeException {
final IOException ioex;
public IORuntimeException(IOException ioex) {
this.ioex = ioex;
}
@Override
public String getMessage() {
return ioex.getMessage();
}
@Override
public StackTraceElement[] getStackTrace() {
return ioex.getStackTrace();
}
//@Override
// ...
}
(Full class available here , as produced by Eclipse "Generate Delegate Methods" macro.) ( 这里提供完整的类,由Eclipse“Generate Delegate Methods”宏生成。)
Usage: 用法:
try {
...
} catch (IOException ioex) {
throw new IORuntimeException(ioex);
}
If you're considering the other answer's use of Unsafe (I recommend not, but anyway), another option is to abuse generics to throw a checked exception with this evil pair of methods (from http://james-iry.blogspot.co.uk/2010/08/on-removing-java-checked-exceptions-by.html ): 如果您正在考虑另一个答案是使用Unsafe(我建议不要,但无论如何),另一种选择是滥用泛型用这种邪恶的方法抛出一个检查异常(来自http://james-iry.blogspot.co .uk / 2010/08 / on-removal-java-checked-exceptions-by.html ):
@SuppressWarnings("unchecked")
private static <T extends Throwable, A>
A pervertException(Throwable x) throws T {
throw (T) x;
}
public static <A> A chuck(Throwable t) {
return Unchecked.
<RuntimeException, A>pervertException(t);
}
You might also check out com.google.common.base.Throwables.getRootCause(Throwable)
and just print its (root) stack trace. 您还可以查看
com.google.common.base.Throwables.getRootCause(Throwable)
并打印其(根)堆栈跟踪。
听起来你实际上需要检查例外情况
As of Java 8 there's another way: 从Java 8开始,还有另一种方法:
try {
// some code that can throw both checked and runtime exception
} catch (Exception e) {
throw rethrow(e);
}
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.