Object-Oriented Programming - Lecture 6: Exceptions - Lê Hồng Phương

✦ What is an exception? ✦ Catching and handling exceptions ✦ Specifying the exceptions thrown by a method ✦ How to throw exceptions ✦ Advantages of exceptions ✦ Exercises

pdf31 trang | Chia sẻ: candy98 | Lượt xem: 543 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Object-Oriented Programming - Lecture 6: Exceptions - Lê Hồng Phương, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
August 2012 Object-Oriented Programming Lecture 6: Exceptions Dr. Lê H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH 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 2 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 program’s 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. 3 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. 4 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. 5 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 6 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. 7 Thursday, August 9, 12 Catching and handling exceptions public class ListOfNumbers { private List list; private static final int SIZE = 10; public ListOfNumbers() { list = new ArrayList(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 ArrayList’s 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. ✦ In our example: try { // code } catch and finally blocks . . . 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: ✦ Example: try { // code } catch (ExceptionType e1) { // code } catch (ExceptionType e2) { // code } 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, it’s 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. ✦ Recall that ArrayIndexOutOfBoundsException is an unchecked exception, so we can just write the following: public void writeList() throws IOException, ArrayIndexOutOfBoundsException { 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 by using the throw statement. ✦ The Java platform provides many exception classes. All the classes are descendants of the Throwable class. ✦ Syntax: throw someThrowableObject; ✦ Throwable objects are instances of any subclass Throwable. public Object pop() { Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; } 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: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } • What happens if the file can't be opened? • What happens if the length of the file can't be determined? • What happens if enough memory can't be allocated? • What happens if the read fails? • 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 { 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; } readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } 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 error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else 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