用运行时exception替换已检查的exception?
鉴于我基本上想要消除已检查的exception使用并将它们转换为运行时exception,我通常会做这样的事情:
try { file.read(); } catch (IOException e){ throw new RuntimeException(e); }
这样做有几个缺点,但最让我烦恼的是我的运行时exception将包含嵌套的堆栈跟踪。 基本上我想将“IOException”作为RuntimeException(或“IORuntimeException”)重新抛出原始消息和stacktrace,这样我就可以避免无用的嵌套堆栈跟踪。 我在中间某处重新抛出exception的“事实”对我来说似乎只是无用的噪音。
这可能吗 ? 有没有这样做的图书馆?
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 // ... }
( 这里提供了完整的类,由Eclipse“Generate Delegate Methods”宏生成。)
用法:
try { ... } catch (IOException ioex) { throw new IORuntimeException(ioex); }
跟进我的评论。 这篇文章必须对这个问题有所了解。 它使用sun.misc.Unsafe
来重新抛出exception而不包装它们。
如果你正在考虑使用不安全的另一个答案(我建议不要,但无论如何),另一个选择是滥用generics用这种邪恶的方法抛出一个检查exception(来自http://james-iry.blogspot.co .uk / 2010/08 / on-removal-java-checked-exceptions-by.html ):
@SuppressWarnings("unchecked") private static A pervertException(Throwable x) throws T { throw (T) x; } public static A chuck(Throwable t) { return Unchecked. pervertException(t); }
您还可以查看com.google.common.base.Throwables.getRootCause(Throwable)
并打印其(根)堆栈跟踪。
听起来你实际上需要检查例外
从Java 8开始,还有另一种方法:
try { // some code that can throw both checked and runtime exception } catch (Exception e) { throw rethrow(e); } @SuppressWarnings("unchecked") public static RuntimeException rethrow(Throwable throwable) throws T { throw (T) throwable; // rely on vacuous cast }
*更多信息在这里 。