gpt4 book ai didi

java - 如何在 Java 中将未检查的异常转换/包装为已检查的异常?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:11:28 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com