Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中将未检查的异常转换/包装为已检查的异常?_Java_Exception_Checked Exceptions_Unchecked Exception - Fatal编程技术网

如何在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)); }

在Java中,是否可以将未检查的异常转换为已检查的异常?
如果是,请建议如何将未检查的异常转换/包装为已检查的异常。

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

例如:

  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);
}

并且通常在构造函数中添加原因。