Sie sind auf Seite 1von 31

Object-Oriented Programming

Lecture 6: Exceptions
Dr. L H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH

August 2012
1

Thursday, August 9, 12
Content

What is an exception?

Catching and handling exceptions

Specifying the exceptions thrown by a method

How to throw exceptions

Advantages of exceptions

Exercises

Thursday, August 9, 12
What is an exception?

An exception is an event, which occurs during the execution of a


program, that disrupts the normal flow of the programs instructions.

When an exception occurs within a method, the method creates an


exception object and hands it off to the runtime system.

The exception object contains information about the error (its type,
the state of the program when the error occurred).

Creating an exception object and handing it to the runtime system is


called throwing an exception.

Thursday, August 9, 12
What is an exception?

When an exception is thrown, the


runtime system attempts to find
something to handle it.

A set of possible somethings is the


ordered list of methods that had been
called to get to the method where the
error occurred.

This list of methods is known as call


stack.

Thursday, August 9, 12
What is an exception?
The runtime system searches the call stack for a method that can handle the
exception.

The block of code that handles the exception is called exception handler.

The type of exception object thrown must match the type that can be
handled by the handler.

When the handler is found, the runtime passes the exception to the handler.

Thursday, August 9, 12
Content

What is an exception?

Catching and handling exceptions

Specifying the exceptions thrown by a method

How to throw exceptions

Advantages of exceptions

Exercises

Thursday, August 9, 12
Catching and handling exceptions

3 exception handler components: try, catch and finally blocks.

An example: ListOfNumbers

Creates an ArrayList that contains 10 Integer elements;

Specifies a methods named writeList() which writes the list to a text


file called output.txt.

Thursday, August 9, 12
Catching and handling exceptions
public class ListOfNumbers {

private List<Integer> list;


private static final int SIZE = 10;

public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}

public void writeList() {


PrintWriter out = new PrintWriter(new FileWriter("output.txt"));

for (int i = 0; i < SIZE; i++) {


out.println("Value at: " + i + " = " + list.get(i));
}
out.close();
}
} 8

Thursday, August 9, 12
Checked and unchecked
exceptions
The constructor new FileWriter("output.txt") initializes an output stream to a file.

If the file cannot be opened, the constructor throws an IOException.

The call to the ArrayLists get method list.get(i) may throw an


IndexOutOfBoundException if the value of its argument is invalid (negative
or larger than the size of the list).

There are two possible exceptions, however, the compiler reports only the
error message thrown by the FileWriter constructor.

The first exception is a checked exception.

The second exception is an unchecked exception.


9

Thursday, August 9, 12
The try block

Enclose the code that might throw an exception within a try block.

try {
// code
}
catch and finally blocks . . .

In our example:
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt"));

for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch ...
10

Thursday, August 9, 12
The catch blocks

Catch blocks are directly after the try block:


try {
// code
} catch (ExceptionType e1) {
// code
} catch (ExceptionType e2) {
// code
}

Example: try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
throw new SampleException(e);

} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} 11

Thursday, August 9, 12
The catch blocks

In Java SE 7 and later, a single catch block can handle multiple types of
exception.
catch (IOException | SQLException ex) {
logger.log(ex);
throw ex;
}

12

Thursday, August 9, 12
The finally block
The finally block always executes when the try block exits.

This ensures that the finally block is executed even if an unexpected


exception occurs.

In the example, the program should close the stream before exiting the
writeList() method. The try block can exit in one of three ways:

The new FileWriter statement fails and throws an IOException.

The list.get(i) statement fails and throws an


ArrayIndexOutOfBoundsException.

Everything succeeds and the try block exits normally.


13

Thursday, August 9, 12
The finally block

The finally block is a perfect place to perform cleanup regardless of


what happens within the try block.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}

14

Thursday, August 9, 12
The complete example
public void writeList() {
PrintWriter out = null;

try {
System.out.println("Entering" + " try statement");

out = new PrintWriter(new FileWriter("output.txt"));


for (int i = 0; i < SIZE; i++)
out.println("Value at: " + i + " = " + list.get(i));

} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: "
+ e.getMessage());

} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());

} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
} 15

Thursday, August 9, 12
Content

What is an exception?

Catching and handling exceptions

Specifying the exceptions thrown by a method

How to throw exceptions

Advantages of exceptions

Exercises

16

Thursday, August 9, 12
Specifying the exceptions thrown
by a method
We have seen how exceptions can be handled by a method.

Sometimes, its better to let a method further up the call stack handle
the exceptions.

In this case, the method must specify that it can throw the exceptions
that could occur within its code.
public void writeList() throws IOException, ArrayIndexOutOfBoundsException {

Recall that ArrayIndexOutOfBoundsException is an unchecked exception, so we


can just write the following:
public void writeList() throws IOException {
17

Thursday, August 9, 12
Content

What is an exception?

Catching and handling exceptions

Specifying the exceptions thrown by a method

How to throw exceptions

Advantages of exceptions

Exercises

18

Thursday, August 9, 12
How to throw exceptions

Any code can throw an exception public Object pop() {


Object obj;
by using the throw statement.
if (size == 0) {
throw new EmptyStackException();
The Java platform provides many
}
exception classes. All the classes are
descendants of the Throwable class. obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
Syntax: throw someThrowableObject; return obj;
}

Throwable objects are instances


of any subclass Throwable.

19

Thursday, August 9, 12
Throwable class and its subclasses

Failures
of the JRE

Exception: IllegalAccessException, NegativeArraySizeException...


RuntimeException: NullPointerException, ArithmeticException...

20

Thursday, August 9, 12
Content

What is an exception?

Catching and handling exceptions

Specifying the exceptions thrown by a method

How to throw exceptions

Advantages of exceptions

Exercises

21

Thursday, August 9, 12
Advantages of exceptions

Advantage 1: Separating error-handling code from regular code.

Exceptions separate details of what to do when something out of


the ordinary happens from the main logic of a program.

Consider the pseudocode method that reads an entire file into


memory:
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
22

Thursday, August 9, 12
Advantages of exceptions

Advantage 1: Separating error-handling code from regular code.

Exceptions separate details of what to do when something out of


the ordinary happens from the main logic of a program.

Consider the pseudocode method that reads an entire file into


memory:
What happens if the file can't be opened?
readFile {
What happens if the length of the file can't be
open the file;
determined?
determine its size;
What happens if enough memory can't be
allocate that much memory;
allocated?
read the file into memory;
What happens if the read fails?
close the file;
What happens if the file can't be closed?
}
22

Thursday, August 9, 12
errorCodeType readFile {
initialize errorCode = 0;

open the file;


if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
23

Thursday, August 9, 12
errorCodeType readFile { readFile {
initialize errorCode = 0; try {
open the file;
open the file; determine its size;
if (theFileIsOpen) { allocate that much memory;
determine the length of the file; read the file into memory;
if (gotTheFileLength) { close the file;
allocate that much memory; } catch (fileOpenFailed) {
if (gotEnoughMemory) { doSomething;
} catch (sizeDeterminationFailed) {
read the file into memory;
doSomething;
if (readFailed) {
} catch (memoryAllocationFailed) {
errorCode = -1; doSomething;
} } catch (readFailed) {
} else { doSomething;
errorCode = -2; } catch (fileCloseFailed) {
} doSomething;
} else { }
errorCode = -3; }
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
23

Thursday, August 9, 12
Advantages of exceptions

Advantage 2: Propagating errors up the call stack.

Suppose that the readFile() method is the fourth method in a series


of nested methods calls made by the main program.
method1 {
call method2;
}

method2 {
call method3;
}

method3 {
call readFile;
}
24

Thursday, August 9, 12
Advantages of exceptions

Suppose that the method1 is the only method interested in the error
that might occur within readFile.

Traditional error-notification techniques:

method1 { errorCodeType method2 { errorCodeType method3 {


errorCodeType error; errorCodeType error; errorCodeType error;
error = call method2; error = call method3; error = call readFile;
if (error) if (error) if (error)
doErrorProcessing; return error; return error;
else else else
proceed; proceed; proceed;
} } }

25

Thursday, August 9, 12
Advantages of exceptions

In Java, only the methods that care about errors have to worry about
detecting errors.
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}

method2 throws exception {


call method3;
}

method3 throws exception {


call readFile;
}
26

Thursday, August 9, 12
Advantages of exceptions

Advantage 3: Grouping and differentiating error types.

The grouping and categorizing exceptions is a natural outcome of


the class hierarchy.

} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: "
+ e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}

27

Thursday, August 9, 12
Content

What is an exception?

Catching and handling exceptions

Specifying the exceptions thrown by a method

How to throw exceptions

Advantages of exceptions

Exercises

28

Thursday, August 9, 12
Exercises

Exercise 1. Write the program which was asked in the midterm test.
Note the use of exceptions in your code.

Exercise 2. Is there anything wrong with the following exception


handler as written? Will this code compile?
try {

} catch (Exception e) {

} catch (ArithmeticException a) {

}

29

Thursday, August 9, 12

Das könnte Ihnen auch gefallen