Hi. Altough there are many threads about this topic "exception being thrown by JVM / Programmatically" (and I already read all of these), but still I can't see the difference and I will try to be more clear than the other posts by showing an example of this (confusing) point.
Questions number 5 from chapter 6 says: Which of the following exceptions are thrown by the JVM? And among the options there are two: NullPointerException (the right answer is thown by jvm) and NumberFormatException (right answer, thrown by the programmer). And my question is why.
NullPointerException and NumberFormatException are unchecked and if I do this:
String cad = null;
cad.trim() // NullPointerException (thrown by jvm)
Integer.parseInt("abc"); // NumberFormatException (thrown by the programmer)
So my question is why if both are unchecked exceptions, in the second example we say that NumberFormatException is thrown by the programmer. What does it do NumberFormatException to be thrown by the programmer if I didn't anything different than in case of NullPointerException?. Can someone tell me please which is the difference that I can't see? .
Hi Dave. Thanks for your answer. So I realize based in your answer that NulPointerException is thrown by jvm becase it is never present on the signature of a method by "throws" (altough i can make a method that throws a NullPointerException) unlike NumberFormatException that is actually present in methods like parseInt. So for this, NumberFormatException is programatically and NullPointer by jvm. Is this right for you?.
Basically, but the more important question is: Why?
And the answer is that sometimes the JVM simply doesn't know how to continue.
The most common situations that arise inside a program are NPE (NullPointerException) and integer division by 0 (ArithmeticException), but there are other problems, like stack overflows and I/O issues, that the JVM can't recover from, so it throws an exception automatically.
Part of your job, as a programmer, is to foresee potential problems (especially NPEs) and try to deal with them before they happen so that the JVM doesn't have to.
Hope it helps.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here