Java Reference
In-Depth Information
Now when you try to run this code, you will receive a
null pointer exception
, as shown in
Figure 6-8.
figure 6-8
This looks very similar to the
ArithmeticException
you saw in the retirement fund examples.
However, here, because you have more than just the
main
method, there is some further information
about the location where the exception occurred. You can see from the first line the type of excep-
tion and that it occurred during the execution of the
main
method. After that, it's easier to read
from the bottom up to try to find the exact cause of the error. During the execution, there was an
error at line 7, when the
printPerson()
method was called. The execution then jumps to the body
of that method and the exception occurred during line 13 of the
printPerson()
method. In that
line, the only reference was to
myPerson.job.JobName
, so you know that the
job
or
JobName
was
never initialized for the
Person
object referenced by
myPerson
.
myPerson
references
employee
from
line 7.
One way to avoid this kind of situation is by requiring initialization as part of the constructor.
Previously, you saw empty constructors for
Person
and
JobType
. This means that when you create a
Person
object, you do not specify a name, age, or job type. Depending on the system you are creating,
there may be reasons to leave some of these empty when you create a new person. For example, if you
create a
Person
object as soon as you start a job search, you may only know the job type. On the other
hand, if you create a
Person
object as soon as someone applies to work at your company, you may only
know their name and age, but not which job you will hire them for (if you hire them at all). However,
if you create a
Person
object precisely when you hire a person for a specific job, you'll have all three
pieces of information at creation. This last situation is implemented here, where all the information
is known and can be initialized in the constructor. In real applications, you may need more than one
constructor to handle different cases, but if you leave some fields null, you will need to handle
null
pointer exceptions
in other ways. To avoid this, you might decide to create a
JobType
for every
case, including
Interviewee
for people who have not yet been hired or
NewHire
for new employees
who have not been given a specific
JobType
. Alternatively, you could have a Boolean method
hasJob-
Type()
check whether the
Person
already has a
JobType
assigned and handle these cases as needed.
public class ExceptionExamples {
public static void main(String[] args) {
JobType manager = new JobType("Manager", 6);
Person employee = new Person("Bob Little", 47, manager);
Search WWH ::
Custom Search