Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

 

Chapter 11 Exceptions and Assertions

Table 11-2.  Important Subclasses of the RuntimeException Class

 

 

Class

Short Description

ArithmeticException

Thrown when arithmetic errors occur, such as attempting to divide by zero.

BufferOverflowException,

Thrown for an attempt to write beyond a buffer’s limits.

BufferUnderflowException

 

ClassCastException

Thrown when an attempt is made to cast between incompatible types (such

 

as String to Integer type or vice versa).

NegativeArraySizeException

Thrown when an attempt is made to create an array of negative size.

NoSuchElementException

Thrown when an attempt is made to use the nextElement() method on an

 

Enumeration when no more values exist to access.

NullPointerException

When an attempt is made to de-reference through a null reference.

UnsupportedOperationException

Thrown when an attempt is made to apply an operation that is not supported

 

or that does not exist (for example, attempting to write to a read-only file

 

system will result in throwing a ReadOnlyFileSystemException, which is a

 

derived class of this exception).

IllegalArgumentException

Thrown when an incorrect or inappropriate argument is passed to a method.

IndexOutOfBoundsException

Thrown when an attempt is made to access the data structure using

 

an index value that is not within the permissible range; base class of

 

ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException.

 

 

The Error Class

When the JVM detects a serious abnormal condition in the program, it raises an exception of type Error. When you get an exception of Error or its subtypes, the exception is not meant for you to handle. The best course of action is to let the program crash! Why? Let’s discuss a trivial example to understand this.

Assume that you try to run a program that does not exist! For example, consider the UnCheckedExceptionExample3 class that you saw in Listing 11-16; if you make a mistake in the capitalization of the class name and try to invoke it, you’ll get NoClassDefFoundError.

D:\ > java UncheckedExceptionExample3

Exception in thread "main" java.lang.NoClassDefFoundError: UncheckedExceptionExample3 (wrong name: UnCheckedExceptionExample3)

at java.lang.ClassLoader.defineClass1(Native Method)

at java.lang.ClassLoader.defineClass(ClassLoader.java:791)

at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)

at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361)

at java.net.URLClassLoader$1.run(URLClassLoader.java:355)

at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356)

at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)

341

Chapter 11 Exceptions and Assertions

As the helpful part of the stack trace indicates (“wrong name: UnCheckedExceptionExample3”), you have given a class to load that does not exist by the given name (note that names in Java are case-sensitive). So, the JVM responded with a NoClassDefFoundError.

Let’s consider a programming example to understand how an error could occur. Assume that you’re writing a recursive method to calculate the factorial of a number and forget to put in the right termination condition (see Listing 11-18).

Listing 11-18.  NonTerminatingRecursion.java

class NonTerminatingRecursion {

        // factorial is a recursive call

        static int factorial(int n) {

                int result = 0;

                // Assume that the following termination condition statement is missing ...

                // if(n == 0) return 1;

                result = factorial(n - 1) * n;

                return result;

        }

        public static void main(String ... args) {

                System.out.println("factorial of 4 is: " + factorial(4));

        }

}

When run, this program crashes after throwing this exception:

Exception in thread "main" java.lang.StackOverflowError

        at NonTerminatingRecursion.factorial(NonTerminatingResursion.java:7)

        at NonTerminatingRecursion.factorial(NonTerminatingResursion.java:7)

         [... this at "NonTerminatingRecursion.factorial(NonTerminatingResursion.java:7)" is repeated a large number of times...]

For each method call, the JVM creates a runtime structure called a stack frame in its stack area. Since the recursive call, the JVM keeps creating such stack frames, and after some time, it exhausts the stack area. At this point, the JVM cannot continue its execution, so it throws the StackOverflowError. When you get a StackOverflowError, you can almost be sure that it is a programming error that caused this exception. You need to fix the program to avoid raising this exception.

Exceptions of type Error indicate an abnormal condition in the program. There is no point in catching this exception and trying to continue execution and pretending nothing has happened. It is a really bad practice to do so!

Table 11-3 provides a list of important subclasses of the Error class.

342

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]