From a class extending 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);
}
}
will cause the true stack trace to be lost.
IllegalArgumentException 确实具有带有Throwable
cause
参数的Throwable
函数-该代码根本不使用它们,这可能是因为它比Java 5中引入的“ Exceptions具有Throwable
cause
”约定更旧。
Use initCause :
try {
throw new IOException();
} catch (IOException e) {
IllegalStateException ise = new IllegalStateException();
ise.initCause(e);
throw ise;
}
Not as pleasant, but will do the job.
It seems a curious omission. Generally it's used like this:
if (value == null) {
throw new IllegalArgumentException("Value can't be null");
}
But as you've demonstrated there are occasions where taking an exception would be useful. One of those quirks that makes Java so fun. In the above I'd simply extract the exception message. The context should be clear.
Prior to Java SE 5, IllegalArgumentException did not accept a Throwable cause. In Java SE 5 and later, it does.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.