1 / 42

OO Design and Programming II Chapter 17 Exception Handling

OO Design and Programming II Chapter 17 Exception Handling. What is an Exception?. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

rafiki
Download Presentation

OO Design and Programming II Chapter 17 Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OO Design and Programming II Chapter 17Exception Handling CS262

  2. What is an Exception? • An exceptionis an event that occurs during the execution of a program that disrupts the normal flow of instructions. • When an error 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, including its type and state of the program when the error occurred. • Creating an exception object and handing it to the runtime system is called throwing an exception. CS262

  3. Method where exception occurred Method call Method without an exception handler Method call Method that has an exception handler Method call main The call stack CS262

  4. Method where error occurred Throws exception Looking for appropriate handler “ducks” Method without an exception handler Looking for appropriate handler Method that has an exception handler not caught Catches exception main When an error occurs, the runtime system searches the call stack for an appropriate error handler CS262

  5. Catch and Specify • Catch: a method can catch an exception by providing an exception handler for that type of exception. • Specify: If a method chooses not to catch an exception, the method must specify that it can throw that exception. CS262

  6. Two kinds of Exceptions • Runtime exceptions • Arithmetic exceptions • Pointer exceptions (accessing an object’s members via null reference) • Indexing exceptions (accessing array element) • Non-runtime exception (also called checked exception) • I/O CS262

  7. The Throwable CLass Object Throwable Error Exception unchecked IOException RuntimeException MyException checked unchecked CS262

  8. Checked or Unchecked Exceptions Unchecked Exceptions CS262

  9. Runtime exceptions • Arithmetic exceptions • See example: BJ_Exceptions/Exc0.java • compiled but runtime error • BJ_Exceptions/Exc1.java • Compare Exc0 and Exc1 when the exception occurs • See the stack trace when exception occurs CS262

  10. Writing your own Handler • Examples Exc0.java and Exc1.java use the Java run-time environment exception handlers • Write your own handlers with • try • catch • Examples: • BJ_Exceptions/Exc2.java • BJ_Exceptions/HandleErrorA.java • BJ_Exceptions/HandleErrorB.java CS262

  11. Not just one catch • Multiple catches are allowed in a try-catch statement • Examples: • BJ_Exceptions/Multicatch.java • Caution: Exception subclasses must precede their exception superclasses. Otherwise the subclasses are not reachable • Example: BJ_Exceptions/SuperSubCatch.java CS262

  12. Nested try clauses • A try clause can be nested in another try. • Each time a try clause is entered, the context of that exception is pushed on the stack. • If an inner try clause does not have a catch handler for a particular exception, the stack is unwound and the next try clause's catch handlers are inspected for a match. This continues until one of the catch clauses succeeds, or until all of the nested try statements are exhausted. • If no catch clause matches, then the Java run-time environment system will handle the exception. • Example: BJ_Exception/NestTry.java CS262

  13. You can be a pitcher too • So far you have been catching exceptions • You can throw exceptions too • General form of throw: • throw ThrowableInstance • Primitive types, non-Throwable classes e.g. String and Object cannot be used as exceptions • Two ways to obtain a Throwable object: • using a parameter in a catch phrase • creating a Throwable object with the new operator CS262

  14. Method must declare a throw • If method does not catch, don’t just throw but you need to declare up front for intention to throw • General form of method declaration that includes a throws clause type method-name(parameter-list) throws exception-list { // body of method } CS262

  15. Examples • BJ_Throw/IncorrectThrowsDemo.java • BJ_Throw/CorrectThrowsDemo.java • BJ_Throw/ThrowDemo.java CS262

  16. try-catch--finally try { Java statements } catch (ExceptionType e1) {//exception Java Statements //handler } catch (ExceptionType e2) { Java Statements } finally { // optional Java Statements // If present, // always executes // close files // cleanup } CS262

  17. Lab • To determine the number of characters, words, and lines in a file • Use FileReader to read a text file • Use a simple finite state machine to count the number of words or lines CS262

  18. FileReader To construct a FileReader, use the following constructors: public FileReader(String filename) public FileReader(File file) Ref: http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html A java.io.FileNotFoundException would occur if you attempt to create a FileReader with a nonexistent file. CS262

  19. How to read with FileReader // Create an input stream input = new FileReader("temp.txt"); int code; /* Repeatedly read a character and display it on the console*/ while ((code = input.read()) != -1) System.out.print((char)code); CS262

  20. // To catch I/O exceptions try { // Create an input stream // Repeatedly read a character and display it on the console } catch (FileNotFoundException ex) { System.out.println("File temp.txt does not exist"); } catch (IOException ex) { ex.printStackTrace(); } finally { try { input.close(); // Close the stream } catch (IOException ex) { ex.printStackTrace(); } } CS262

  21. FSM to count number of lines CS262

  22. FSM to count words WS are white space characters: ‘’, ‘\t’, or ‘\n’ CS262

  23. checked exceptions Source Code Review and DemoListOfNumbers0.java new FileWriter("OutFile.txt") // Note this But in http://java.sun.com/j2se/1.5.0/docs/api/ FileWriter throws an exception public FileWriter(String fileName) throws IOException CS262

  24. Exercise 5.1 • Go to directory “Ex5.1 Checked Exceptions” • 1. Down load and compile ListOfNumers0.java as is. • 2. Study the changes in ListOfNumbers1.java and compile. • 3. Study the changes in ListOFNumbers2.java and compile CS262

  25. try-catch--finally try { Java statements } catch (ExceptionType e1) {//exception Java Statements //handler } catch (ExceptionType e2) { Java Statements } finally { // optional Java Statements // If present, // always executes // close files // cleanup } CS262

  26. An Example public void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("i + " = " + vector.elementAt(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"); } } } CS262

  27. Source Code Review and Demo Directory “Ex5.2 Checked Exceptions” ListOfNumbers.java ListOfNumbersTest.java CS262

  28. Exercise 5.2 • Down load and run ListOfNumersTest.java as is. • Change outFile.txt to read-only and run it again • Change outFile.txt back to r/w • Change “i<size” to (i<=size) in ListOfNumbers.java • Compile and run again • Change the program back CS262

  29. throw • We have looked at catching exceptions thrown by the Java Runtime system • Your program may also throw an exception • throw ThrowableInstance; • ThrowableInstance is an object of type Throwable or a subclass of Throwable CS262

  30. Exceptions Thrown by a Method public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException(); obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; } *The EmptyStackException class is defined in the java.util package. CS262

  31. The Throwable CLass Object Throwable Error Exception unchecked IOException RuntimeException MyException unchecked CS262

  32. What can you throw? • Error deals with internal errors and resource exhaustion • Not much you can do if it occurs • You should not throw a object of this type • Exception Hierarchy • Focus on Exception • Runtime exception is due to a programming error • I/O exceptions may occur to a good program CS262

  33. Examples • RuntimeExceptions • A bad cast • An out-of-bounds array access • A null pointer access • Non RuntimeExceptions: • Trying to read past the end of a file • Trying to open a malformed URL • Trying to find a class object for a string that does not denote an existing class CS262

  34. Where do you advertise your method may throw? • In the header of the method • For example: readLine of BufferedReader public StringreadLine() throws IOException http://java.sun.com/j2se/1.4.2/docs/api/java/io/BufferedReader.html#BufferedReader(java.io.Reader) • Returns a String • May also throw an IOException • If such exception occurs, runtime system will search for an exception handler. CS262

  35. To Advertise a throw or Not • You don’t have to advertise every possible throwable object • Then when and what you have to advertise? • An exception is thrown in 4 situations: • You call a method that throws a checked exception, for example, the readLine method of the BuffredReader class • You detect an fault and throw a checked exception with the throw statement • You make a programming error, such as array[-1] = 0 and that gives rise to an unchecked exception such as ArrayIndexOutOfBoundsException • An internal error occurs in the virtual machine or runtime library CS262

  36. To Advertise a throw or Not • For cases 1 and 2, you must tell the programmers who will use your method that there is the possibility of an exception • Why? Any method that throws an exception may terminate the thread • For cases 3 and 4, you should not and need not advertise • Why? • You should fix the unchecked runtime exception instead of advertising its possibility. It is completely under your control • You cannot fix internal Java errors CS262

  37. Source Code Review and DemoBJ_ExceptionInPackage\ExceptionDemo.java Exercise .3: download and run ExceptionDemo.java CS262

  38. Why Exceptions? • Separating error handling code from regular code. • Propagating errors up the call stack towards the callers • Grouping and differentiating error messages and types CS262

  39. Advantage 1 – Separating Error-Handling code from Regular Code 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; } } CS262

  40. Advantage 2 – Propagating Errors Up the Call Stack method1 { // Only I am interested in errors try { call method2; } catch (Exception e) { doErrorProcessing; } } method2 throws Exception { // ‘throws’needed // to duck call method3; } method3 throws Exception { call readFile; } CS262

  41. Advantage 3 Object Throwable Error Exception IOException RuntimeException MyException CS262

  42. Exercise 5.4 • What are the exceptions you see in Assignment #4? • No command line arguments • Cannot open input files • Empty employee data file • Data format (syntax) errors • Data semantic errors (sup does not exist) • Table overflow CS262

More Related