Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Similar presentations


Presentation on theme: "Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:"— 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 1. Separating Error Handling Code from Regular Code 2. Propagating Errors Up the Call Stack 3. Grouping Error Types and Error Differentiation

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

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 method1 { call method2; } method2 { call method3; } method3 { call readFile; } method1 method2 method3 readFile 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? call

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; } method1 method2 method3 readFile Call Stack call return

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

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 ArithmeticException NullPointerException IOException FileNotFoundException MalformedURLException

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

14 Throwing Structure method1 method2 method3 method4 Call Stack call throw 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 method1 method2 method3 method4 Call Stack call throw 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 method1 method2 method3 method4 Call Stack call throw

19 FileCopy Example Revisited import java.io.*; public class FileCopy1 { 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 4% java FileCopy1 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. (FileInputStream.java:103) at java.io.FileInputStream. (FileInputStream.java:66) at java.io.FileReader. (FileReader.java:39) at FileCopy.main(FileCopy.java:12) 5% In the example, the main method chooses to ''pass the buck'', but there is nowhere to pass it to. Thus, the program will crash:

21 Catching the Exception public class FileCopy2 { 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 This approach will catch the first instance of a FileNotFoundException, but only that instance: 5% java FileCopy2 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. (FileInputStream.java:103) at java.io.FileInputStream. (FileInputStream.java:66) at java.io.FileReader. (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 FileCopy3 { 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 FileCopy3 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 Exception s and Error s are both subclasses of the Throwable class: Object Throwable ErrorException LinkageErrorThreadDeathVirtualMachineError

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

33 Multi Catch In Java 7 or later, it is possible to handle more than one type of exception in a single catch block try{ //allocate system resource } catch (Exception1 ¦ Exception2 ex){ // exception handling } MultiCatchDemo.java In multi catch, the catch parameter (above ex) is implicitly final. So it is not possible to assign any values to it within the catch block.

34 Try With Resources In Java 7 or later, it is possible to use a try-with-resources statement which is a try declares on resources that is auto closable. The resource defined in the try-with-resource must implement the java.lang.AutoCloseable interface Prior to Java7, we use the finally block TryWithResourceDemo.java

35 Polymorphism Jiafan Zhou

36 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.

37 Encapsulation vs. Polymorphism Encapsulation  Encapsulation creates new data types by combining characteristics and behaviors.  Implementation hiding separates the interface from the implementation by making the details private Polymorphism  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.

38 Late Binding  Late binding is also called  Dynamic binding  or Runtime binding

39 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.

40 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); }

41 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.

42 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

43 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); }

44 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.

45 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.

46 Method-callbinding  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)

47 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:

48 The inheritance diagram

49 Late binding Shape s = new Circle(); //simply upcasting You can say, “a cricle is a shape” 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).

50 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

51 Add new instruments

52 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"; }

53 Music3 example public class Music3 { // Doesn't care about type, so new types // added to the system still work right: public static void tune(Instrument i) { //... i.play(Note.MIDDLE_C); } public static void tuneAll(Instrument[] e){ for(int i = 0; i < e.length; i++) tune(e[i]); } public static void main(String[] args) { // Upcasting during addition to the array: Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() }; tuneAll(orchestra); } "Wind.play() Middle C", "Percussion.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C", "Woodwind.play() Middle C" tune( ) does not know the code changes that have happened around it. polymorphism is an important technique for the programmer to “separate the things that change from the things that stay the same”.

54 Pitfall: “overriding” private methods public class PrivateOverride { private void f() { System.out.println("private f()"); } public static void main(String[] args) { PrivateOverride po = new Derived(); po.f(); } class Derived extends PrivateOverride { public void f() { System.out.println("public f()"); } "private f()" Remember: a private method is automatically final, and is also hidden from the derived class. So Derived’s f( ) in this case is a brand new method. It’s not even overloaded, since the base-class version of f( ) isn’t visible in Derived.

55 Abstract classes and methods  In all previous instrument examples, the methods in the base class Instrument were always “dummy” methods.  If these methods are ever called, you’ve done something wrong.  That’s because the intent of Instrument is to create a common interface for all the classes derived from it

56 Abstract class & method  The only reason to establish this common interface is so it can be expressed differently for each different subtype.  Another way of saying this is to call Instrument an abstract base class (or simply an abstract class).  Instrument expresses only the interface, not implementation, you’ll probably want to prevent the user from creating object from it.

57 Abstract Method  One solution: let methods in base class print error message whenever being invoked.  This delays the information until the run time. It’s better to catch the problem at the compile time.  Java provides a mechanism for doing this called the abstract method.  This is a method that is incomplete; it has only a declaration and no method body. abstrct void f();

58 Abstract Class  A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class itself must be qualified as abstract.  You cannot create an object of an abstract class, since an abstract class is incomplete.  This way, the compiler ensures the purity of the abstract class, and you don’t need to worry about misusing it.  It’s possible to create a class as abstract without including any abstract methods. This is useful when you want to prevent any instance from this class.

59 Inherit from Abstract Class  If you inherit from an abstract class and you want to make objects of the new type, you must provide method definitions for all the abstract methods in the base class.  Otherwise, then the derived class is also abstract, and the compiler will force you to qualify that class with the abstract keyword.

60 Abstract Instrument

61 abstract class Instrument { private int i; // Storage allocated for each public abstract void play(Note n); public String what() { return "Instrument"; } public abstract void adjust(); } class Wind extends Instrument { public void play(Note n) { System.out.println("Wind.play() " + n); } public String what() { return "Wind"; } public void adjust() {} } class Percussion extends Instrument { public void play(Note n) { System.out.println("Percussion.play() " + n); } public String what() { return "Percussion"; } public void adjust() {} } class Stringed extends Instrument { public void play(Note n) { System.out.println("Stringed.play() " + n); } public String what() { return "Stringed"; } public void adjust() {} } class Brass extends Wind { public void play(Note n) { System.out.println("Brass.play() " + n); } public void adjust() { System.out.println("Brass.adjust()"); } class Woodwind extends Wind { public void play(Note n) { System.out.println("Woodwind.play() " + n); } public String what() { return "Woodwind"; } }

62 public class Music4 { // Doesn't care about type, so new types // added to the system still work right: static void tune(Instrument i) { //... i.play(Note.MIDDLE_C); } static void tuneAll(Instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); } public static void main(String[] args) { // Upcasting during addition to the array: Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() }; tuneAll(orchestra); } "Wind.play() Middle C", "Percussion.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C", "Woodwind.play() Middle C" There’s really no change except in the base class. It’s helpful to create abstract classes and methods because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used

63 Designing with inheritance  You might think “everything ought to be inherited, because polymorphism is such a clever tool.”  This can burden your designs!! You code will become needlessly complicated.  A better approach is to choose composition first, especially when it’s not obvious which one you should use.

64 abstract class Actor { public abstract void act(); } class HappyActor extends Actor { public void act() { System.out.println("HappyActor"); } class SadActor extends Actor { public void act() { System.out.println("SadActor"); } class Stage { private Actor actor = new HappyActor(); public void change() { actor = new SadActor(); } public void performPlay() { actor.act(); } public class Transmogrify { public static void main(String[] args) { Stage stage = new Stage(); stage.performPlay(); stage.change(); stage.performPlay(); } "HappyActor", "SadActor" A Stage object contains a reference to an Actor, which can be dynamically bound to different object. The behavior produced by performPlay( ) changes which gives dynamic flexibility at run time. This is called State Pattern in Design Pattern.

65 Pure inheritance vs. extension  Pure inheritance: only methods established in the base class or interface are to be overridden in the derived class. derived class will have the interface of the base class and nothing less. derived classes will also have no more than the base-class interface.

66 “Is-a” The base class can receive any message you can send to the derived class because the two have exactly the same interface. All you need to do is upcast from the derived class and never look back to see what exact type of object you’re dealing with.

67 “Is-Like-a” the derived class is like the base class— it has the same fundamental interface but it has other features that require additional methods to implement

68 Drawback of Is-Like-a  The extended part of the interface in the derived class is not available from the base class.  so once you upcast, you can’t call the new methods:

69 Downcast  You lose the specific type information via an upcast.  To retrieve the type information: move back down the inheritance hierarchy—you use a downcast.  upcast is always safe; the base class cannot have a bigger interface than the derived class.  But with a downcast, you don’t really know that a shape (for example) is actually a circle.

70 There must be some way to guarantee that a downcast is correct. You get a ClassCastException. At run time this cast is checked to ensure that it is in fact the type you think it is. In java this scheme is called run-time type identification (RTTI) What will happen if it isn’t?

71 class Useful { public void f() {} public void g() {} } class MoreUseful extends Useful { public void f() {} public void g() {} public void u() {} public void v() {} public void w() {} } public class RTTI { public static void main(String[] args) { Useful[] x = { new Useful(), new MoreUseful() }; x[0].f(); x[1].g(); // Compile time: method not found in Useful: //! x[0].u(); ((MoreUseful)x[1]).u(); // Downcast/RTTI ((MoreUseful)x[0]).u(); // Exception thrown }

72 Homework

73 Update your existing banking system with proper inheritance hierarchy. Design the object model of the banking system e.g. Current account, deposit account etc. Design the exception in your banking system. Update the client(menu) that uses the banking system

74 Questions & Answers

75 75 Mock Exam Questions: Question 4 4. Given: 31. // some code here 32. try { 33. // some code here 34. } catch (SomeException se) { 35. // some code here 36. } finally { 37. // some code here 38. } Under which three circumstances will the code on line 37 be executed? (Choose three.) A. The instance gets garbage collected. B. The code on line 33 throws an exception. C. The code on line 35 throws an exception. D. The code on line 31 throws an exception. E. The code on line 33 executes successfully.

76 76 Mock Exam Questions: Question 19 Given: 1. class TestA { 2. public void start() { System.out.println(”TestA”); } 3. } 4. public class TestB extends TestA { 5. public void start() { System.out.println(”TestB”); } 6. public static void main(String[] args) { 7. ((TestA)new TestB()).start(); 8. } 9. } What is the result? A. TestA B. TestB C. Compilation fails. D. An exception is thrown at runtime.

77 77 Mock Exam Questions: Question 21 Given: 11. public abstract class Shape { 12. int x; 13. int y; 14. public abstract void draw(); 15. public void setAnchor(int x, int y) { 16. this.x = x; 17. this.y = y; 18. } 19. } and a class Circle that extends and fully implements the Shape class. Which is correct? A. Shape s = new Shape(); s.setAnchor(10,10); s.draw(); B. Circle c = new Shape(); c.setAnchor(10,10); c.draw(); C. Shape s = new Circle(); s.setAnchor(10,10); s.draw(); D. Shape s = new Circle(); s->setAnchor(10,10); s->draw(); E. Circle c = new Circle(); c.Shape.setAnchor(10,10); c.Shape.draw();

78 78 Mock Exam Questions: Question 27 Given: 11. public static void parse(String str) { 12. try { 13. float f= Float.parseFloat(str); 14. } catch (NumberFormatException nfe) { 15. f= 0; 16. } finally { 17. System.out.println(f); 18. } 19. } 20. public static void main(String[] args) { 21. parse(”invalid”); 22. } What is the result? A. 0.0 B. Compilation fails. C. A ParseException is thrown by the parse method at runtime. D. A NumberFormatException is thrown by the parse method at runtime.

79 79 Mock Exam Questions: Question 57 Given: 11. Float pi = new Float(3.14f); 12.if(pi>3) { 13. System.out.print(”pi is bigger than 3. “); 14. } 15. else { 16. System.out.print(”pi is not bigger than 3. “); 17. } 18. finally { 19. System.out.println(”Have a nice day.”); 20. } ‘What is the result? A. Compilation fails. B. pi is bigger than 3. C. An exception occurs at runtime. D. pi is bigger than 3. Have a nice day. E. pi is not bigger than 3. Have a nice day.

80 80 Mock Exam Questions: Question 68 Click the Exhibit button. SomeException: 1. public class SomeException { 2. } Class A: 1. public class A { 2. public void doSomething() { } 3. } Class B: 1. public class B extends A { 2. public void doSomething() throws SomeException { } 3. } Which is true about the two classes? A. Compilation of both classes will fail. B. Compilation of both classes will succeed. C. Compilation of class A will fail. Compilation of class B will succeed. D. Compilation of class B will fail. Compilation of class A will succeed.

81 81 Mock Exam Questions: Question 69 Click the Exhibit button. Class TestException 1. public class TestException extends Exception { 2. } Class A: 1. public class A { 2. 3. public String sayHello(String name) throws TestException { 4. 5. if(name == null) { 6. throw new TestException(); 7. } 8. 9. return “Hello “+ name; 10. } 11. 12. } A programmer wants to use this code in an application: 45. A a=new A(); 46. System.out.println(a.sayHello(”John”)); Which two are true? (Choose two.) A. Class A will not compile. B. Line 46 can throw the unchecked exception TestException. C. Line 45 can throw the unchecked exception TestException. D. Line 46 will compile if the enclosing method throws a TestException. E. Line 46 will compile if enclosed in a try block, where TestException is caught.

82 82 Mock Exam Questions: Question 70 Given: 33. try { 34. // some code here 35. } catch (NullPointerException e1) { 36. System.out.print(”a”); 37. } catch (RuntimeException e2) { 38. System.out.print(”b”); 39. } finally { 40. System.out.print(”c”); 41. } What is the result if a NullPointerException occurs on line 34? A. c B. a C. ab D. ac E. bc F. abc

83 83 Mock Exam Questions: Question 71 Given: 11.classA { 12. public void process() { System.out.print(”A,”); } } 13. class B extends A { 14. public void process() throws IOException { 15. super.process(); 16. System.out.print(”B,”); 17. throw new IOException(); 18. } } 19. public static void main(String[] args) { 20. try { new B().process(); } 21. catch (IOException e) { System.out.println(”Exception”); } } What is the result? A. Exception B. A,B,Exception C. Compilation fails because of an error in line 20. D. Compilation fails because of an error in line 14. E. A NullPointerException is thrown at runtime.

84 84 Mock Exam Questions: Question 72 Given: 11.classA { 12. public void process() { System.out.print(”A “); } } 13. class B extends A { 14. public void process() throws RuntimeException { 15. super.process(); 16. if (true) throw new RuntimeException(); 17. System.out.print(“B”); }} 18. public static void main(String[] args) { 19. try { ((A)new B()).process(); } 20. catch (Exception e) { System.out.print(”Exception “); } 21. } What is the result? A. Exception B. A Exception C. A Exception B D. A B Exception E. Compilation fails because of an error in line 14. F. Compilation fails because of an error in line 19.

85 85 Mock Exam Questions: Question 73 Given: 11. public classA { 12. void process() throws Exception { throw new Exception(); } 13. } 14. public class B extends A { 15. void process() { System.out.println(”B “); } 16. } 17. public static void main(String[] args) { 18.A a=new B(); 19. a.process(); 20.} What is the result? A. B B. The code runs with no output. C. An exception is thrown at runtime. D. Compilation fails because of an error in line 15. E. Compilation fails because of an error in line 18. F. Compilation fails because of an error in line 19.

86 86 Mock Exam Questions: Question 74 Given: 11. public class A { 12. void process() throws Exception { throw new Exception(); } 13. } 14. public class B extends A { 15. void process() { System.out.println(”B”); } 16. } 17. public static void main(String[] args) { 18. new B().process(); 19. } What is the result? A. B B. The code runs with no output. C. Compilation fails because of an error in line 12. D. Compilation fails because of an error in line 15. E. Compilation fails because of an error in line 18.

87 87 Mock Exam Questions: Question 75 Given: 84. try { 85. ResourceConnection con = resourceFactory.getConnection(); 86. Results r = con.query(”GET INFO FROM CUSTOMER”); 87. info = r.getData(); 88. con.close(); 89. } catch (ResourceException re) { 90. errorLog.write(re.getMessage()); 91. } 92. return info; Which is true if a ResourceException is thrown on line 86? A. Line 92 will not execute. B. The connection will not be retrieved in line 85. C. The resource connection will not be closed on line 88. D. The enclosing method will throw an exception to its caller.


Download ppt "Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:"

Similar presentations


Ads by Google