Java Reference
In-Depth Information
7. “address must be set first”);
8. }
9. System.out.println(“Shipping order...”);
10. }
11. }
Invoking
shipOrder
on a
CustomerOrder
object with a null
address
fi eld results in the
following exception:
Exception in thread “main” java.lang.IllegalStateException: address must be set
first
at CustomerOrder.shipOrder(CustomerOrder.java:6)
at CustomerOrder.main(CustomerOrder.java:12)
NullPointerException
A
NullPointerException
is thrown when a
null
reference is used in situations where an
actual object is required. This exception is one that is thrown frequently by both the JVM
and programmatically. For example, the JVM throws a
NullPointerException
in the
following code:
3. Integer x = null;
4. System.out.println(x.intValue());
The reference
x
is null, so attempting to invoke any method on it results in a
NullPointerException
. The stack trace looks like:
Exception in thread “main” java.lang.NullPointerException
at NullPointerDemo.main(NullPointerDemo.java:4)
Programmatically, you can throw a
NullPointerException
if you know a reference is
null
. For example, the following method throws a
NullPointerException
if the argument
passed in is a
null
reference:
public void printMessage(String message) {
if(message == null) {
throw new NullPointerException(“message cannot be null”);
}
System.out.println(message);
}
NumberFormatException
A
NumberFormatException
is thrown when a string is parsed into a numeric value and the
string does not have the appropriate format. The exception is thrown by the parsing and
Search WWH ::
Custom Search