1 / 26

Lecture 7

Lecture 7. Internet Computing Using Java Theophano Mitsa UMASS-Dartmouth. Method overriding and calling the superclass method version: Here the overridden method getA() will be called. MySubClass2 extends MyClass{ private int b;

nubia
Download Presentation

Lecture 7

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. Lecture 7 Internet Computing Using Java Theophano Mitsa UMASS-Dartmouth

  2. Method overriding and calling the superclass method version: Here the overridden method getA() will be called. MySubClass2 extends MyClass{ private int b; //Constructor MySubClass2(int val, int b) { super(val); /this.b = b; System.out.println("The subclass constructor is called"); }; public int getA() { System.out.println("The overridden method has been called"); return (super.getA()); } //Member methods public static void main(String args[]) { MySubClass2 ref1 = new MySubClass2(1,2); System.out.println(" a is" + ref1.getA()); }} CONCLUSION: So, we can use super, not only to invoke superclass constructors, but also superclass methods

  3. Overridding continued • Note: It is the class of the object at run time, that determines whether the superclass or subclass version of method will be called. • Note: You can NOT override a final method. • Note: It is an error to have an overridden method in a subclass have more restricted access than the superclass method. • Question: What would happen if instead of super.getA(), we said return(this.a)? • Question: What would happen if we said getA(), instead of super.getA();

  4. Questions continued • Question: What would happen if in SubClass2’s main we had this line instead? MyClass ref1 = new MySubClass2(1,2); • Question: What would happen if in SubClass2’s main we had this line instead? MyClass ref1 = (MyClass) new MySubClass2(1,2); • Question: What would happen if in SubClass2’s main we had this line instead? MyClass ref1 = new MyClass(1);

  5. What will this program print out? class MySubClass2 extends MyClass{ private int b; //Constructor MySubClass2(int val, int b) { super(val); this.b = b; System.out.println("The subclass constructor is called"); }; public int getA(int val) { System.out.println("The overridden method has been called"); return (super.getA()); } //Member methods public static void main(String args[]) { MySubClass2 ref1 = new MySubClass2(1,2); System.out.println(" a is" + ref1.getA()); }} It will print out 1 (the original getA method is called).

  6. Exception handling • Definion of Exception: A problem that occurs during a program’s execution. • Exception Handling: Enables a program to handle exceptions -> this makes the program become fault-tolerant.

  7. Exception handling • Exception handling is designed for synchronous errors -> errors that occur while the program is executing. Example: division by zero, invalid method parameter, out-of-range array indices, failed memory allocation. • Exception handling is not for problems with asynchronous events such as disk I/O completion, mouse clicks, etc. These are events that occur outside of the flow of control of the program. • Important note: Incorporate exception handling in your design process.

  8. The Exception Hierarchy • Exceptions in Java are objects. • Exceptions in Java are derived from the java.lang.Throwable. java.lang. Throwable java.io. Exception IOException Error RuntimeException ArithmeticException NullPointerException

  9. Explaining the Exception Hierarchy • The Error class and its subclasses define exceptions that deal with thread problems, virtual machine problems, etc. These are never caught and the program can not recover from them. • RuntimeException class: Examples of subclasses are ArrayIndexOutofBoundsException, NullPointerException (uninitialized references), ArithmeticException etc. These are caused by bugs, which we should fix in our programs and not try to catch them with Exceptions.

  10. Exception handling terminology • When a method detects a problem it can’t handle, it throws an exception. • If there is an exception handler, then it will catch and handle the exception. • Leaving a program without catching an exception can leave resources in a bad state. Such resources include file handle, database connections, network connection, etc.

  11. Checked versus unchecked exceptions • RuntimeExceptions, Error and their subclasses: The compiler does not check to see that we provide an Exception Handler for them. For this reason, they are called unchecked exceptions. • All other exceptions are checked exceptions, in the sense that the compiler complains, if it sees a method that can throw an exception and we haven’t provided an exception handler.

  12. An exception handler try { statements that might cause exception } catch(exception type, parameter) { statements to be executed when the above exception type occurs } finally { statements that are always executed independent of whether an exception occurs or not }

  13. public class MyException1 { public static void main(String args[]) { int a=1; int b = 0; int c; try { c = a/b; System.out.println("I did a division\n"); } catch(ArithmeticException e) { System.out.println("Division with zero exception caught.\n"); } finally { System.out.println("I am done."); } System.out.println("I have some more statements to execute.\n"); } }

  14. About the try-catch-finally exception handler • It is a syntax error to place code between a try and its corresponding catch block. • It is a compilation error to catch the exact same type of exception in two catch statements. • It is OK though if you catch an exception in one catch block and then a superclass exception in another. • For each try block, there can be many catch blocks, but only one finally block. • Note: the finally block is optional.

  15. The finally block • A finally block usually contains code that releases resources acquired in a try block, such as file, network, and database connections. • What about object references and memory leaks? Java performs automatic garbage collection and it therefore avoids most memory leaks.

  16. A scenario • Let say a resource is allocated in a try block. • 1st: An exception occurs: In this case (as in the example we ran), the rest of the try statement is skipped. If we have a catch block that catches the exception, the statements of this catch block are executed next. Then the finally block releases the resource and the statements after the finally block are executed. • 2nd: Let say no exception occurs inside the try block. Then the try block is executed fully, the catch statements are skipped, and the finally block statements are executed which release the resource. Then, the statements after the finally block are then executed. • Experimentation: In the previous example, replace b with a nonzero number and see what happens.

  17. 3rd: An exception occurs, but it is not caught. In this case, the rest of the try block statements are skipped, and the finally block statements are executed.Then the program passes up the exception to the calling method. • Experimentation:Remove the catch block and see what happens. • Experimentation: Leave the catch block and remove the try block.

  18. Some more notes about try-catch-finally • An exception can be “catchable” in many catch blocks. • Let say we divide by zero. This can be caught in a catch block that catches ArithmeticException, or it can be caught in a block that catches Exception. • Only the first catch block that can catch the exception is executed and the rest catch blocks are skipped. Experimentation: In the example, put a catch block that catches Exception and see what happens.

  19. The throw Statement • It is possible for a method to throw an exception, using the throw statement. public class MyException2 { public static void main(String args[]) { int a=1; int b = 3; int c; try { if(b==3) throw new DividebyThreeException("Oops!"); c = a/b; System.out.println("I did a division\n"); } catch(DividebyThreeException e) { System.out.println(e); } finally { System.out.println("I am done."); } System.out.println("I have some more statements to execute.\n"); }} class DividebyThreeException extends Exception { DividebyThreeException(String msg) { super(msg); } }

  20. Experimentation • Remove the throw statement in the previous example and see what happens • Remove the catch block and see what happens.

  21. The throws statement • Summarizing, a method can throw an exception, either by using the throw statement or by invoking another method that throws an exception. • The method can either catch the exception using a try-catch-block or it can pass up the exception to the calling method using the throws statement.

  22. public class MyException2 { public static void main(String args[]) throws DividebyThreeException { int a=1; int b = 3; int c; if(b==3) throw new DividebyThreeException("Oops!"); c = a/b; System.out.println("I did a division\n"); System.out.println("I have some more statements to execute.\n"); } } class DividebyThreeException extends Exception { DividebyThreeException(String msg) { super(msg); } }

  23. public class MyException2 { public static void main(String args[]) { try { division(); } catch(DividebyThreeException e) { System.out.println(e); } System.out.println("I have some more statements to execute.\n"); } static void division() throws DividebyThreeException{ int a=1; int b = 3; int c; if(b==3) throw new DividebyThreeException("Oops!"); c = a/b; System.out.println("I did a division\n"); } } class DividebyThreeException extends Exception { DividebyThreeException(String msg) { super(msg); } }

  24. Note • The exception specified in the throws statement can be a superclass of the actual Exception thrown in the throw statement.

  25. Exercise • In the multiplier program, write a new exception, when the user attempts to multiply with 1000.Throw and catch the exception.

  26. References • Your textbook • K.A. Mughal and R.W.Rasmussen, A Programmer’s Guide to Java Certification, Addison-Wesley.

More Related