3

Java中的Unchecked Exceptions可以转换成Checked Exceptions吗?如果是,请提出将未检查异常转换/包装为已检查异常的方法。

4

2 回答 2

2

您可以用已检查的异常包装未检查的异常

try {
    // do something
} catch (RuntimeException re) {
    throw new CheckedException("Some message", re);
}
于 2014-12-14T20:13:41.440 回答
2

是的。您可以捕获未检查的异常并抛出已检查的异常。

例子 :

  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);
  }
于 2014-12-14T20:09:10.970 回答