Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.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 为什么IllegalArgumentException(JDK 1.4.2)不能用可丢弃的原因构造?_Java_Exception_Exception Handling - Fatal编程技术网

Java 为什么IllegalArgumentException(JDK 1.4.2)不能用可丢弃的原因构造?

Java 为什么IllegalArgumentException(JDK 1.4.2)不能用可丢弃的原因构造?,java,exception,exception-handling,Java,Exception,Exception Handling,从扩展java.beans.PropertyEditorSupport的类: /** * Sets the property value by parsing a given String. May raise * java.lang.IllegalArgumentException if either the String is * badly formatted or if this kind of property can't be expressed * as text. *

从扩展java.beans.PropertyEditorSupport的类:

/**
 * Sets the property value by parsing a given String.  May raise
 * java.lang.IllegalArgumentException if either the String is
 * badly formatted or if this kind of property can't be expressed
 * as text.
 *
 * @param text  The string to be parsed.
 */
public void setAsText(String name) {
    try {
        asEnum(name);
    } catch (InvalidEnumNameException e) {
        throw new IllegalArgumentException("Unable to convert value: "+ name);
    }
}

将导致真正的堆栈跟踪丢失

这似乎是一个奇怪的遗漏。通常是这样使用的:

if (value == null) {
   throw new IllegalArgumentException("Value can't be null");
}

但是,正如您所展示的,在某些情况下,采取例外是有用的。让Java变得如此有趣的怪癖之一。在上面,我只提取异常消息。上下文应该是清楚的。

IllegalArgumentException采用了一个
可丢弃的
原因
参数-该代码根本不使用它们,可能是因为它比Java5之前引入的“Exceptions have a
Throwable
原因
”约定旧,IllegalArgumentException不接受可丢弃的原因。 在Java SE 5及更高版本中,它确实如此。

使用:


虽然不是那么令人愉快,但可以完成任务。

如果是这样,你就不走运了-原因参数在1.5之前的大多数(所有?)异常中都不存在
try {
  throw new IOException();
} catch (IOException e) {
  IllegalStateException ise = new IllegalStateException();
  ise.initCause(e);
  throw ise;
}