Monday, February 14, 2011

Chapter 30: Common Exceptions and Errors

In this chapter we are going to take a look at the common exceptions and errors you may encounter whilst your career as a Java programmer. Some of them are: ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError, or NoClassDefFoundError.

Where Exceptions Come From

Jump back a page and take a look at the previous chapter. 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 are 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. 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:
static String s;
public static void main(String [] args) {

Surely, the compiler can find the problem with that tiny little program! 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 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() { // Bad Recursion Example

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 one of our previous chapters.

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 (actually, it’s not an exception, but it IS thrown programmatically), and throwing an IllegalArgumentException. In fact, our API developer could have used IllegalArgumentException 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

Some of the common exceptions you may encounter in the exam are:

1. ArrayIndexOutOfBoundsException - Thrown when attempting to access an array with an invalid index value (either negative or beyond the length of the array).
2. ClassCastException - Thrown when attempting to cast a reference variable to a type that fails the IS-A test.
3. IllegalArgumentException - Thrown when a method receives an argument formatted differently than the method expects.
4. IllegalStateException - Thrown when the state of the environment doesn’t match the operation being attempted, e.g., using a Scanner that’s been closed.
5. NullPointerException - Thrown when attempting to access an object with a reference variable whose current value is null.
6. NumberFormatException - Thrown when a method that converts a String to a number receives a String that it cannot convert.
7. AssertionError - Thrown when a statement’s boolean test returns false.
8. ExceptionInInitializerError - Thrown when attempting to initialize a static variable or an initialization block.
9. StackOverflowError - Typically thrown when a method recurses too deeply. (Each invocation is added to the stack.)
10. NoClassDefFoundError - 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.

Previous Chapter: Chapter 29 - Exception Handling

Next Chapter: Chapter 31 - Assertions

1 comment:

  1. It would really help if you used code tags for the code.


© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.


Google+ Followers