如何在Java中将未经检查的异常转换/包装为Checked Exceptions?

时间:2014-12-14 20:08:35

标签: java exception checked-exceptions unchecked-exception

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

2 个答案:

答案 0 :(得分: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);
  }

答案 1 :(得分:2)

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

try {
    // do something
} catch (RuntimeException re) {
    throw new CheckedException("Some message", re);
}