Java Reference
In-Depth Information
common exceptions
There are some exceptions that occur often enough, not just with new programmers, but even with
experienced developers. In this short section, you'll get to see two in particular that come up all the time:
null pointer exceptions and index out of bounds exceptions. There are explanations and examples
that will help you recognize when, where, and why these exceptions might pop up in your programs.
Null pointer exceptions indicate that the program is trying to access an object that doesn't exist
yet. Before you can reference a primitive data type, like int , you need to initialize it, which is setting
the value. If you forget to do this, Eclipse will warn you, like it did for other syntax errors. When
you declare a variable of a composite data type, you are actually creating a pointer to an object.
Now, if you declare a variable without assigning an object to point to, you are left with a pointer
to null or, in other words, you are pointing at nothing. Then trying to access that variable's object
will likely result in a null pointer exception . Usually, if it's obvious, Eclipse will complain about
this, too. But it is possible that the references are not so straightforward and the problem is not a
syntax error. In that case, you will encounter a null pointer exception . Consider the following
examples, which illustrate these concepts.
public class ExceptionExamples {
public static void main(String[] args) {
Person employee;
printPerson(employee);
}
public static void printPerson(Person myPerson){
System.out.println(myPerson.name + " is " + myPerson.age + " years old.");
}
}
class Person{
String name;
int age;
Person (){
}
}
note In some of these examples, you'll notice that instance variables, name
and age, of a Person object are accessed directly through the myPerson
instance. In Chapter 4, encapsulation and information hiding principles were
introduced, but you'll see this in much more detail in Chapter 9. It is discouraged
to access variables directly, but instead you should use accessor methods like
getName() to return the person's name. To keep the examples in this chapter
simple, getter and setter methods are not included in every code example, but
it is good practice to get in the habit of creating these methods to access fields.
 
Search WWH ::




Custom Search