1 / 83

Exception

Exception. Jiafan Zhou. Java Exception Handling. Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: Examples: Hard disk crash; Out of bounds array access; Divide by zero, etc

gilda
Download Presentation

Exception

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. Exception Jiafan Zhou

  2. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: Examples: Hard disk crash; Out of bounds array access; Divide by zero, etc When an exception occurs, the executing method creates an Exception object and hands it to the runtime system--``throwing an exception'' The runtime system searches the runtime call stack for a method with an appropriate handler, which ``catches the exception''

  3. Exception Policy Java is fussy about (some) exceptions, requiring that the programmer either: deal with the exceptions when they occur, using try and catch, or explicitly hand off the exception to the method that calls the method in which the exception occurs, effectively ``passing the buck'' to the calling method. The exceptions Java is fussy about are called ''checked'' exceptions, because the compiler will check that one of the above options is satisfied

  4. Advantages of Java Exception Handling Separating Error Handling Code from Regular Code Propagating Errors Up the Call Stack Grouping Error Types and Error Differentiation

  5. Advantage 1:Separating Error Handling Code from ``Regular'' Code Example: Here is pseudocode for reading a file into memory: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }

  6. Problems with readFile 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?

  7. Error Handling With Traditional Programming 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; }

  8. Error Handling With Java 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; } } Note that the error handling code and ``regular'' code are separate

  9. Advantage 2:Propagating Errors Up the Call Stack readFile method1 { call method2; } method2 { call method3; } method3 { call readFile; } call method3 call method2 call method1 Call Stack Suppose also that method1 is the only method interested in the errors that occur within readFile. How does the error code get propogated up the stack?

  10. Propagating Errors Using Traditional Programming 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; } readFile return call method3 return call method2 return call method1 Call Stack

  11. Propagating Errors Using Java method1{ try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } readFile call method3 throw call method2 call method1 Call Stack

  12. Advantage 3:Grouping Error Types and Error Differentiation Java exceptions are first class Java objects, and so they are grouped into a class hierarchy. For example: Exception RunTimeException IOException NullPointerException FileNotFoundException ArithmeticException MalformedURLException

  13. Example Suppose (remember, this is pseudocode): method1 { try { call method2; } catch(Exception) { doErrorProcessing; } } method2 throws ArithmeticException { ... call method3; ... } method3 throws FileNotFoundException { ... call method4; ... } method4 throws NullPointerException { ... }

  14. Throwing Structure method4 call method3 call throw method2 call method1 Call Stack In this case, the exception handler in method1 must handle all exception types

  15. Modified Example method1 { try { call method2; } catch(RunTimeException) { doErrorProcessing; } } method2 throws ArithmeticException { ... call method3; ... } method3 throws FileNotFoundException { ... call method4; ... } method4 throws NullPointerException { ... }

  16. New Throwing Structure method4 call method3 throw call method2 call method1 Call Stack In this case, method1 will handle only runtime exceptions. Any FileNotFoundException thrown by method3 will have to be handled further down the stack.

  17. Another Modified Example method1 { try { call method2; } catch(RunTimeException) { doErrorProcessing; } } method2 throws ArithmeticException { try { ... call method3; ... } catch(IOException) { doMoreErrorProcessing; } } method3 throws FileNotFoundException { ... call method4; ... } method4 throws NullPointerException { ... }

  18. New Throwing Structure method4 call method3 throw call method2 call method1 Call Stack

  19. FileCopy Example Revisited import java.io.*; public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r; FileWriter w; System.out.print("Source file name: "); String inFileName = br.readLine(); r = new FileReader(inFileName); System.out.print("Destination file name: "); String outFileName = br.readLine(); w = new FileWriter(outFileName); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); } }

  20. If The Input File Does Not Exist In the example, the main method chooses to ``pass the buck,'' but there is nowhere to pass it to. Thus, the program will crash: 4% java FileCopy Source file name: foo Exception in thread "main" java.io.FileNotFoundException: foo (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:103) at java.io.FileInputStream.<init>(FileInputStream.java:66) at java.io.FileReader.<init>(FileReader.java:39) at FileCopy.main(FileCopy.java:12) 5%

  21. Catching the Exception public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r; FileWriter w; System.out.print("Source file name: "); String inFileName = br.readLine(); try { r = new FileReader(inFileName); } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); System.out.print("Source file name: "); inFileName = br.readLine(); r = new FileReader(inFileName); } ... } }

  22. Catching the Exception (cont'd) This approach will catch the first instance of a FileNotFoundException, but only that instance: 5% java FileCopy Source file name: foo foo (No such file or directory) Source file name: bar Exception in thread "main" java.io.FileNotFoundException: bar (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:103) at java.io.FileInputStream.<init>(FileInputStream.java:66) at java.io.FileReader.<init>(FileReader.java:39) at FileCopy.main(FileCopy.java:19) 6% Note that you can use the getMessage() method (inherited by the Exception class) in your handler.

  23. Generating True Looping Behavior public class FileCopy { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = null; FileWriter w = null; boolean fileFound; do { fileFound = true; System.out.print("Source file name: "); String inFileName = br.readLine(); try { r = new FileReader(inFileName); } catch(FileNotFoundException ex) { fileFound = false; System.out.println(ex.getMessage()); } } while ( !fileFound ); ... } }

  24. New Output 226% java FileCopy Source file name: foo foo (No such file or directory) Source file name: bar bar (No such file or directory) Source file name: foo foo (No such file or directory) Source file name: bar bar (No such file or directory) Source file name: X.java Destination file name: Y.java 227%

  25. Another Way public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = getFileReader(br); FileWriter w = getFileWriter(br); int c; while ((c = r.read()) != -1) w.write(c); w.flush(); }

  26. A Version of main that Does Not throw public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = getFileReader(br); FileWriter w = getFileWriter(br); int c; try { while ((c = r.read()) != -1) w.write(c); w.flush(); } catch(IOException ex) { System.out.println(ex.getMessage()); } } Now the program will not crash if/when an I/O error occurs.

  27. Checked vs. Unchecked Exceptions A program that catches all I/O exceptions may still experience a different type of exception (say, a runtime exception) I/O exceptions are ``checked'' by the compiler That is, you are required to either catch them or mention them in a throws clause Unlike I/O exceptions, runtime exceptions are ``unchecked'' That is, you can choose to ignore them at your peril

  28. Some Checked Exceptions IOException and any of its subclasses InterruptedException (thrown when a thread is interrupted) Any exception you invent by subclassing Exception

  29. Some Unchecked Exceptions Subclasses of RuntimeException: ArithmeticException IllegalArgumentException NumberFormatException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException NullPointerException Those that you invent by subclassing RuntimeException

  30. Exceptions vs. Errors Exceptions are processing conditions that a program ought to be able to recover from if it is robust enough Errors are conditions that are ordinarily not recoverable: Death of a thread Linking error Virtual machine error

  31. The Throwable Class Exceptions and Errors are both subclasses of the Throwable class: Object Throwable Exception Error LinkageError ThreadDeath VirtualMachineError

  32. Finally try{ //allocate system resource } catch (Exception1 e){ } catch(Exception2 e){ } finally{ //free up system resource } Statements inside finally block are guaranteed to be executed. With or without thrown exceptions.

  33. Polymorphism Jiafan Zhou

  34. Polymorphism • Poly- means many, morph means changes.Polymorphism means many changes (method behaviours) for the objects. • It provides another dimension of separation of interface from implementation. (decouple what from how) • Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance.

  35. Encapsulation vs. Polymorphism Encapsulation Polymorphism • Encapsulation creates new data types by combining characteristics and behaviors. • Implementation hiding separates the interface from the implementation by making the details private • It deals with decoupling in terms of types. • Inheritance allows the treatment of an object as its own type or its base type • Many types (derived from the same base type) can be treated as one type, and a single piece of code to work on all those different types equally.

  36. Late Binding • Late binding is also called • Dynamic binding • or Runtime binding

  37. Note Class public class Note { private String noteName; private Note(String noteName) { this.noteName = noteName; } public String toString() { return noteName; } public static final Note MIDDLE_C = new Note("Middle C"); public static final Note C_SHARP = new Note("C Sharp"); public static final Note B_FLAT = new Note("B Flat"); // Etc. } This is an “enumeration” class, which has a fixed number of constant objects to choose from. Note.MIDDLE_C, Note.C_SHARP and Note.B_FLAT You can’t make additional objects because the constructor is private. Notice: Java also supports enum class, but here we simulate the use of Java enum.

  38. Instrument & Wind Class public class Instrument { public void play(Note n) { } } public class Wind extends Instrument { // Override the method play(Note): public void play(Note n) { System.out.println("Wind.play(): " + n); } }

  39. Music class public class Music { public static void tune(Instrument i) { i.play(Note.MIDDLE_C); } public static void main(String[] args) { Wind flute = new Wind(); tune(flute); } } • the method Music.tune( ) accepts an Instrument reference, but also anything derived from Instrument.

  40. Forgetting the object type • In Music.java, why intentionally forget the type of an object? • Can we ask tune( ) to simply takes a Wind reference? • If you did that, you’d need to write a new tune( ) for every type of Instrument in your system. • Suppose you add two more classes Stringed and Brass

  41. Stringed and Brass class class Stringed extends Instrument { public void play(Note n) { System.out.println("Stringed.play(): " + n); } } class Brass extends Instrument { public void play(Note n) { System.out.println("Brass.play(): " + n); } }

  42. Music2 class public class Music2 { public static void tune(Wind i) { i.play(Note.MIDDLE_C); } public static void tune(Stringed i) { i.play(Note.MIDDLE_C); } public static void tune(Brass i) { i.play(Note.MIDDLE_C); } public static void main(String[] args) { Wind flute = new Wind(); Stringed violin = new Stringed(); Brass frenchHorn = new Brass(); tune(flute); // No upcasting tune(violin); tune(frenchHorn) } } "Wind.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C" This works, but… Drawback: you must write type-specific methods for each new Instrument class you add. It’s better to just write a single method that takes the base class as its argument, and not any of the specific derived classes! That’s exactly what polymorphism allows you to do.

  43. Question public static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C); } How can the compiler possibly know that this Instrument reference points to a Wind in this case and not a Brass or Stringed? The compiler can’t. To get a deeper understanding of the issue, it’s helpful to examine the subject of binding.

  44. Method-call binding • Connecting a method call to a method body is called binding. • early binding: binding is performed before the program is run by the complier. • late binding: binding occurs at run time, based on the type of object. • Early binding is also called compile binding or static binding. Late binding is also called runtime binding or dynamic binding • All method binding in Java uses late binding unless the method is static or final (private methods are implicitly final)

  45. Producing the right behavior • The classic example in OOP is the “shape” example. • The shape example has a base class called Shape and various derived types: Circle, Square, Triangle, etc. • The inheritance diagram shows the relationships:

  46. The inheritance diagram

  47. Late binding You can say, “a cricle is a shape” Shape s = new Circle(); //simply upcasting Suppose you call one of the base-class methods (that have been overridden in the derived classes): s.draw(); You might expect that Shape’s draw( ) is called And yet the Circle.draw( ) is called because of late binding (polymorphism).

  48. Extensibility • Because of polymorphism, you can add as many new types as you want to the system without changing the tune( ) method. • In a well-designed OOP program, most or all of your methods will communicate only with the base-class interface. Such a program is extensible. • You can add new functionality by inheriting new data types from the base class. The methods that manipulate the base-class interface will not need to be changed at all to accommodate the new classes

  49. Add new instruments

  50. class Instrument { void play(Note n) { System.out.println("Instrument.play() " + n); } String what() { return "Instrument"; } void adjust() {} } class Wind extends Instrument { void play(Note n) { System.out.println("Wind.play() " + n); } String what() { return "Wind”; } void adjust() {} } class Percussion extends Instrument { void play(Note n) { System.out.println("Percussion.play() " + n); } String what() { return "Percussion"; } void adjust() {} } class Stringed extends Instrument { void play(Note n) { System.out.println("Stringed.play() " + n); } String what() { return "Stringed"; } void adjust() {} } class Brass extends Wind { void play(Note n) { System.out.println("Brass.play() " + n); } void adjust() { System.out.println("Brass.adjust()"); } } class Woodwind extends Wind { void play(Note n) { System.out.println("Woodwind.play() " + n); } String what() { return "Woodwind"; } }

More Related