views:

95

answers:

4

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.

A: 

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.

Brian Agnew
+2  A: 

IllegalArgumentException does have constructors that take a Throwable cause parameter - that code simply doesn't use them, possibly because it is older than the "Exceptions have a Throwable cause" convention, which was introduced with Java 5.

Michael Borgwardt
Yes i'm actually stuck in 1.4.2 ...
Benoit Guerout
In that case you're out of luck - the cause parameter was not present in most (all?) Exceptions before 1.5
Michael Borgwardt
A: 

Prior to Java SE 5, IllegalArgumentException did not accept a Throwable cause. In Java SE 5 and later, it does.

Martin OConnor
+1  A: 

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.

McDowell