21
Okey, we all know the normal way to throw a IllegalArgumentException in Java:
throw new IllegalArgumentException(); // 37 characters
But there must be a shorter (as in less characters) ways to do so. How can we produce a java.lang.IllegalArgumentException with even less code?
- The code fragment has to compile and run in java 7.
- No imports/external packages (e.g. not using
java.util.Arrays.toString())- only exception: java.lang because it is automatically imported.
- You can add own methods/classes.
- It must throw a java.lang.IllegalArgumentException
- Edit: the error output (stacktrace) must name it java.lang.IllegalArgumentException, so no subclasses of it.
To have a base to start from:
class Titled {
public static void main(String[] args) {
throw new IllegalArgumentException();
}
}
No, it will not compile because it can throw a
InterruptedException. – luckydonald – 2014-09-06T21:11:45.3131The compiler will error:
unreported exception InterruptedException; must be caught or declared to be thrown– luckydonald – 2014-09-06T21:12:13.173@luckydonald Hm, it does? I tested it on Ideone and it seemed to work. – Doorknob – 2014-09-06T21:14:21.590
1Whoops, Ideone automatically adds
throws Exceptionto themainmethod. I've added a note in my post. – Doorknob – 2014-09-06T21:17:28.373Ideone tends to automatically add
throws java.lang.Exceptionwhich will allow theInterruptedExceptionto pass the compiler. (Also Ideone importsjava.util.*andjava.io.*) – luckydonald – 2014-09-06T21:20:10.8501Mwhahaha! I managed to find my
IllegalArgumentExceptionby memory. No need for tools like grep. Except the changed rules make it invalid. :-( – Justin – 2014-09-06T22:31:13.007@Quincunx sorry about that. But it is still an nice way. – luckydonald – 2014-09-07T12:35:01.307
Is
1.wait(-1)legal in Java? In C# it is. – usr – 2014-09-07T20:18:43.5671@usr No; primitives aren't objects in Java. – Doorknob – 2014-09-07T20:37:16.127
You can get to eleven characters by renaming
argstoaand usinga.wait(-1)instead. – JohnEye – 2014-09-08T14:39:48.613I thought it was illegal to wait on an object unless you owned the object's monitor, via
synchronized. (In this case, it could actually matter, too, since the object representing""is actually the same object representing every other empty string literal.) – AJMansfield – 2014-09-09T12:26:41.393