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? .
In the first case, it's not Java code that is throwing that exception.
It's a part of the JVM that does it.
In the second case, if you look at the parseInt method you'll see the Java code throwing the NumberFormatException.
It was written by a Java programmer.
posted 1 week ago
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?.
posted 1 week ago
It's not the method signature, it's the code itself.
Inside the code for parseInt there are several checks, for example:
and more complex ones that check the individual characters.
That's what makes it a programmer exception. The JVM doesn't have any code inside it to throw this exception.
For a null pointer exception, it can be thrown by the JVM, when you try and call a method on a null reference.
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