Java 中Unchecked Exceptions 可以转换为Checked Exceptions 吗? 如果是,请提出将 Unchecked Exception 转换/包装为 Checked Exception 的方法。
最佳答案
是的。您可以捕获未检查的异常并抛出已检查的异常。
示例:
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);
}
关于java - 如何在 Java 中将未检查的异常转换/包装为已检查的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473519/