如何在Java中将未检查的异常转换/包装为已检查的异常?
在Java中,是否可以将未检查的异常转换为已检查的异常?如何在Java中将未检查的异常转换/包装为已检查的异常?,java,exception,checked-exceptions,unchecked-exception,Java,Exception,Checked Exceptions,Unchecked Exception,在Java中,是否可以将未检查的异常转换为已检查的异常? 如果是,请建议如何将未检查的异常转换/包装为已检查的异常。是。您可以捕获未检查的异常并抛出已检查的异常 例如: public void setID (String id) throws SomeException { if (id==null) throw new SomeException(); try { setID (Integer.valueOf (id)); }
如果是,请建议如何将未检查的异常转换/包装为已检查的异常。是。您可以捕获未检查的异常并抛出已检查的异常 例如:
public void setID (String id)
throws SomeException
{
if (id==null)
throw new SomeException();
try {
setID (Integer.valueOf (id));
}
catch (NumberFormatException intEx) { // catch unchecked exception
throw new SomeException(id, intEx); // throw checked exception
}
}
然后,在选中异常的构造函数中,使用传递的异常调用initCause
:
public SomeException (String id, Throwable reason)
{
this.id = id;
initCause (reason);
}
您可以将未检查的异常与已检查的异常包装在一起
try {
// do something
} catch (RuntimeException re) {
throw new CheckedException("Some message", re);
}
并且通常在构造函数中添加原因。