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

 

Chapter 11 Exceptions and Assertions

Table 11-3.  Important Subclasses of the Error Class

 

 

Class

Short Description

AssertionError

Thrown when an assertion fails (discussed later in this chapter).

IOError

Thrown when a serious I/O error occurs.

VirtualMachineError

Thrown when the JVM itself enters an erroneous state (due to a bug) or when the JVM

 

runs out of resources (such as memory).

OutOfMemoryError

Thrown when the JVM cannot allocate memory anymore; a derived class of

 

VirtualMachineError.

LinkageError

Thrown when the linking performed by the JVM fails (for example, due to a circular

 

class hierarchy in which case the ClassCircularityError will be thrown, which is a

 

derived class of LinkageError).

NoClassDefFoundError

Thrown when attempting to load the definition of a class when the class loader cannot

 

find that class.

StackOverflowError

Thrown when the application has a non-terminating recursive call, or when the

 

application makes too many function calls that the JVM cannot handle; a derived class

 

of VirtualMachineError.

 

 

The Throws Clause

A method can throw checked exceptions; the clause throws specifies these checked exceptions in the method signature. You had a brief look at the throws keyword in the beginning of this chapter. In the throws clause, you list checked exceptions that a method can throw, so understanding checked exceptions is prerequisite for understanding the throws clause. Since we’ve covered checked exceptions in the previous section on exception types, we’ll cover the throws clause now.

Let’s try reading an integer stored in a file named integer.txt in the current directory. There is an overloaded constructor of the Scanner class that takes a File object as input, so let’s try using it. Listing 11-19 shows the program. Will it work?

Listing 11-19.  ThrowsClause1.java

import java.io.*; import java.util.*;

class ThrowsClause1 {

        public static void main(String []args) {

                System.out.println("Reading an integer from the file 'integer.txt': ");

                Scanner consoleScanner = new Scanner(new File("integer.txt")); System.out.println("You typed the integer value: " + consoleScanner.nextInt());

        }

}

This code will result in a compiler error of “unreported exception FileNotFoundException; must be caught or declared to be thrown.” If you look at the declaration of this Scanner method, you’ll see a throws clause:

public Scanner(File source) throws FileNotFoundException {

So, any method that invokes this constructor should either handle this exception or add a throws clause to declare that the method can throw this exception. Add a throws clause to the main() method; see Listing 11-20.

343

Chapter 11 Exceptions and Assertions

Listing 11-20.  ThrowsClause2.java

import java.io.*; import java.util.*;

class ThrowsClause2 {

        public static void main(String []args) throws FileNotFoundException {

                System.out.println("Reading an integer from the file 'integer.txt': ");

                Scanner consoleScanner = new Scanner(new File("integer.txt")); System.out.println("You typed the integer value: " + consoleScanner.nextInt());

        }

}

If you run this program and there is no file named integer.txt, the program will crash after throwing this exception:

Reading an integer from the file 'integer.txt':

Exception in thread "main" java.io.FileNotFoundException: integer.txt (The system cannot find the file specified)

        at java.io.FileInputStream.open(Native Method)

        at java.io.FileInputStream.<init>(FileInputStream.java:138)

        at java.util.Scanner.<init>(Scanner.java:656)

        at ThrowsClause2.main(ThrowsClause2.java:7)

Let’s now extract the code inside the main() method to a new method named readIntFromFile(). You have defined it as an instance method, so you also create an object of the ThrowsClause3 class to invoke this method from the main() method. Since the code inside readIntFromFile() can throw a FileNotFoundException, it has to either introduce a catch handler to handle this exception or declare this exception in its throws clause (see Listing 11-21).

Listing 11-21.  ThrowsClause3.java

import java.io.*; import java.util.*;

class ThrowsClause3 {

        // since this method does not handle FileNotFoundException,

        // the method must declare this exception in the throws clause

        public int readIntFromFile() throws FileNotFoundException {

                Scanner consoleScanner = new Scanner(new File("integer.txt"));

                return consoleScanner.nextInt();

        }

        // since readIntFromFile() throws FileNotFoundException and main() does not handle

        // it, the main() method declares this exception in its throws cause

        public static void main(String []args) throws FileNotFoundException {

                System.out.println("Reading an integer from the file 'integer.txt': "); System.out.println("You typed the integer value: " +

new ThrowsClause3().readIntFromFile());

        }

}

The behavior of the program remains the same in both Listings 11-20 and 11-21. However, Listing 11-21 shows how the main() method also must still declare to throw the FileNotFoundException in its throws clause (otherwise, the program will not compile).

344

Chapter 11 Exceptions and Assertions

Method Overriding and the Throws Clause

When an overridable method has a throws clause, there are many things to consider while overriding that method. Consider the program in Listing 11-22, which implements an interface named IntReader. This interface declares a single method named readIntFromFile() with the throws clause listing a FileNotFoundException.

Listing 11-22.  ThrowsClause4.java

import java.io.*; import java.util.*;

// This interface is meant for implemented by classes that would read an integer from a file interface IntReader {

        int readIntFromFile() throws IOException;

}

class ThrowsClause4 implements IntReader {

        // implement readIntFromFile with the same throws clause

        // or a more general throws clause

        public int readIntFromFile() throws FileNotFoundException {

                Scanner consoleScanner = new Scanner(new File("integer.txt"));

                return consoleScanner.nextInt();

        }

        // main method elided in this code since the focus here is to understand // issues related to overriding when throws clause is present

}

In this code, you can observe few important facts. First, you can declare the throws clause for methods declared in interfaces; in fact, you can provide the throws clause for abstract methods declared in abstract classes as well. Second, the method declared in the IntReader interface declares to throw IOException, which is a more general exception than a FileNotFoundException (Figure 11-3). While implementing a method, it is acceptable to either provide the throws clause listing the same exception type as the base method or a more specific type than the base method. In this case, the readIntFromFile() method lists a more specific exception (FileNotFoundException) in its throws clause against the more general exception of IOException listed in the throws clause of the base method declared in the IntReader interface.

Object

Throwable

Exception

IOException

FileNotFoundException

Figure 11-3.  Class hierarchy of FileNotFoundException

345

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