Here it is given that IllegalArgumentException and IllegalStateException are typically thrown Programmatically. But these exceptions are runtime exceptions and so must typically be thrown by JVM. My understanding is that ALL RuntimeExceptions are thrown by JVM.
First things first --> As per Java laws, All the Runtime exceptions are thrown only by JVM. What we are trying to understand is -> What makes the JVM to throw this kind of an exception?
Ok, Lets take one at a time.
(1) IllegalArgumentException : Java docs says that -> "Thrown to indicate that a method has been passed an illegal or inappropriate argument."
What this mean is -> Programatically, when the logic tries to pass wrong argument to a method, JVM detects that during Runtime and throws this exception.
(2) IllegalStateException Java docs states -> "Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. "
What this mean is -> "The method invocation has happened (i.e the developer has written code to invoke the method during inappropriate time).
Hope this helps!
Bala<br />SCJP 1.4 98%<br />SCBCD 1.3 -- 88%
Joined: Mar 28, 2006
then "ClassCastException" is also typically thrown programmatically?
Joined: Mar 22, 2006
Good catch! ClassCastException.
When we understand what role Java compiler plays & what JVM does, we can easily understand this CLASSCASTEXCEPTION
Lets see what our JAVAC does. JAVAC purely does type checking. A very APT example is given in the Java doc itself!
Object x = new Integer(0); System.out.println((String)x);
What this code does?? Merely type checking. Thats it! During complie time, the compiler does n't care what you are doing with your object. Because, during compile time, there are NO OBJECTS!!!
LETS COME TO RUNTIME NOW!!! THE JVM! This guy is responsible for all the object creation, assigning stuffs. When the above code executes, the JVM cannot cast an INTEGER object to STRING object!!
Thats why it throws the ClassCastException
Again its your mistake (I mean PROGRAMMER's mistake!). Hence Its the result of PROGRAMMATIC RUNTIME ERROR!