Certification Objective Common Exceptions and Errors (Exam Objective 2.6)


Certification Objective —Common Exceptions and Errors (Exam Objective 2.6)

2.6 Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError, or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programmatically.

Exception handling is another area that the exam creation team decided to expand for the SCJP 5 exam. This section discusses the aspects of exceptions that were added for this new version. The intention of Objective 2.6 is to make sure that you arc familiar with some of the most common exceptions and errors you'll encounter as a Java programmer.

image from book
Exam Watch

The questions from this section are likely to be along the lines of, "Here's some code that just did something bad, which exception will be thrown?"

Throughout the exam, questions will present some code and ask you to determine whether the code will run, or whether an exception will be thrown. Since these questions are so common, understanding the causes for these exceptions is critical to your success.

image from book

This is another one of those objectives that will turn up all through the real exam (does "An exception is thrown at runtime" ring a bell?), so make sure this section gets a lot of your attention.

Where Exceptions Come From

Jump back a page and take a look at the last sentence of Objective 2.6. It's important to understand what causes exceptions and errors, and where they come from. For the purposes of exam preparation, let's define two broad categories of exceptions and errors:

  • JVM exceptions Those exceptions or errors that arc either exclusively or most logically thrown by the JVM.

  • Programmatic exceptions Those exceptions that are thrown explicitly by application and/or API programmers.

JVM Thrown Exceptions

Let's start with a very common exception, the NullPointerException. As we saw in Chapter 3, this exception occurs when you attempt to access an object using a reference variable with a current value of null. There's no way that the compiler can hope to find these problems before runtime. Let's look at the following:

 class NPE {   static String s;   public static void main(String [] args) {     System.out.println(s.length());   } } 

Surely, the compiler can find the problem with that tiny little program! Nope, you're on your own. The code will compile just fine, and the JVM will throw a NullPointerException when it tries to invoke the length() method.

Earlier in this chapter we discussed the call stack. As you recall, we used the convention that main() would be at the bottom of the call stack, and that as main() invokes another method, and that method invokes another, and so on, the stack grows upward. Of course the stack resides in memory, and even if your OS gives you a gigabyte of RAM for your program, it's still a finite amount. It's possible to grow the stack so large that the OS runs out of space to store the call stack. When this happens you get (wait for it), a StackOverflowError. The most common way for this to occur is to create a recursive method. A recursive method is one that invokes itself in the method body. While that may sound weird, it's a very common and useful technique for such things as searching and sorting algorithms. Take a look at this code:

 void go() {    //recursion gone bad    go(); } 

As you can see, if you ever make the mistake of invoking the go() method, your program will fall into a black hole; go() invoking go() invoking go(), until, no matter how much memory you have, you'll get a stackOverflowError. Again, only the JVM knows when this moment occurs, and the JVM will be the source of this error.

Programmatically Thrown Exceptions

Now let's look at programmatically thrown exceptions. Remember we defined "programmatically" as meaning something like this:

  • Created by an application and/or API developer.

For instance, many classes in the Java API have methods that take string arguments, and convert these strings into numeric primitives. A good example of these classes are the so-called "wrapper classes" that we studied in Chapter 3.

At some point long ago, some programmer wrote the java.lang.Integer class, and created methods like parseInt() and valueOf(). That programmer wisely decided that if one of these methods was passed a string that could not be converted into a number, the method should throw a NumberFormatException. The partially implemented code might look something like this:

 int parseInt (String s) throws NumberFormatException {   boolean  parseSuccess = false;   int result = 0;   // do complicated parsing   if (!parseSuccess)   // if the parsing failed     throw new NumberFormatException();   return result; } 

Other examples of programmatic exceptions include an AssertionError (okay, it's not an exception, but it IS thrown programmatically), and throwing an IllegalArgumentFxception. In fact, our mythical API developer could have used IllegalArgument Exception for her parseInt() method. But it turns out that NumberFormatException extends IllegalArgumentException, and is a little more precise, so in this case, using NumberFormatException supports the notion we discussed earlier: that when you have an exception hierarchy, you should use the most precise exception that you can.

Of course, as we discussed earlier, you can also make up your very own special, custom exceptions, and throw them whenever you want to. These homemade exceptions also fall into the category of "programmatically thrown exceptions."

A Summary of the Exam's Exceptions and Errors

Objective 2.6 lists ten specific exceptions and errors. In this section we discussed the StackOverflowError. The other nine exceptions and errors listed in the objective are covered elsewhere in this book. Table 5-2 summarizes this list and provides chapter references to the exceptions and errors we did not discuss here.

Table 5-2: Descriptions and Sources of Common Exceptions.

Exception (Chapter Location)

Description

Typically Thrown

ArrayIndexOutOfBoundsException

(Chapter 3, "Assignments")

Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array).

By the JVM

ClassCastException

(Chapter 2, "Object Orientation")

Thrown when attempting to cast a reference variable to a type that fails the IS-A test.

By the JVM

IllegalArgumentException

(Chapter 3, "Assignments")

Thrown when a method receives an argument formatted differently than the method expects.

Programmatically

IllegalStateException

(Chapter 6, "Formatting")

Thrown when the state of the environment doesn't match the operation being attempted, e.g., using a Scanner that's been closed.

Programmatically

NullPointerException

(Chapter 3, "Assignments")

Thrown when attempting to access an object with a reference variable whose current value is null.

By the JVM

NumberFormatException

(Chapter 6, "Formatting")

Thrown when a method that converts a String to a number receives a String that it cannot convert.

Programmatically

AssertionError

(This chapter)

Thrown when a statement's boolean test returns false.

Programmatically

ExceptionInInitializerError

(Chapter 3, "Assignments")

Thrown when attempting to initialize a static variable or an initialization block.

By the JVM

StackOverflowError

(This chapter)

Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.)

By the JVM

NoClassDefFoundError

(Chapter 10, "Development")

Thrown when the JVM can't find a class it needs, because of a command-line error, a classpath issue, or a missing .class file.

By the JVM




SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net