为什么IllegalArgumentException(JDK 1.4.2)不能用throwable原因构造?

时间:2009-09-25 09:03:56

标签: 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.
 *
 * @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);
    }
}

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

4 个答案:

答案 0 :(得分:2)

带有Throwable cause参数的IllegalArgumentException does have constructors - 该代码根本不使用它们,可能是因为它比“异常有Throwable {更旧” {1}}“约定,它是随Java 5引入的。

答案 1 :(得分:1)

使用initCause

try {
  throw new IOException();
} catch (IOException e) {
  IllegalStateException ise = new IllegalStateException();
  ise.initCause(e);
  throw ise;
}

不那么令人愉快,但会胜任。

答案 2 :(得分:0)

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

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

但是,正如你已经证明的那样,有时候采取例外是有用的。其中一个让Java 如此变得有趣的怪癖。在上面我只是提取异常消息。背景应该是明确的。

答案 3 :(得分:0)

在Java SE 5之前,IllegalArgumentException不接受Throwable原因。 在Java SE 5及更高版本中,它确实如此。