1 / 76

Introduction to Computing Using Java

Learn how to handle exceptions in Java, including IO errors and network outages, and explore array and GUI programming. Understand the importance of graceful exception handling and avoiding program crashes.

jgualtieri
Download Presentation

Introduction to Computing Using Java

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. Introduction to Computing Using Java Exception Handling, Array & GUI

  2. Exception (例外/情況/鑊) • When running a program, there may be unexpected conditions or errors. E.g. • Network outage causing read error. • I/O Error (disk damage, disk full, etc.) • It’s an art to handle the exceptions gracefully and correctly. • We won’t expect a blue screen during the course of running our programs! X

  3. Exceptionally Ugly

  4. How to Deal With Exceptions • Each exception is given a meaningful name, indicating the nature of it. • We may define our own exceptions with our given names. • Java has already defined some commonly used ones. • IOException, ArithmeticException, EOFException, etc. • In any method, we may: • Raise exceptions (throw) • Detect exceptions (try) and Handle exceptions (catch) • Ignore exceptions (declarethrows clause and propagate) • Ignore means the method would suicide. • The suicided method would become a killer (exception propagation).

  5. IOException Objects • Used when something gone wrong during general Input/Output operations. • We may create (new) an IOException object from the class java.io.IOException. import java.io.*; ... ... new IOException();

  6. Throwing IOException • If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else ... return answer; } … void main(…) { double value = tan(30); } Normal return

  7. Throwing IOException • If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else ... return answer; } … void main(…) { double value = tan(30); } Abnormal return “throwing exception”

  8. Throwing IOException • If we found/felt something wrong with I/O, we may create and throw an IOException object to the message sender. double tan(double angle) { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else ... return answer; } … void main(…) { double value = tan(30); } Rest skipped, method terminated

  9. Still Something Wrong:Exception Declaration • If we compile the above “program”, we will get a compilation error. • We have to tell message senders: be ready to receive (possible) IOException’s: declaration. double tan(double angle) throws IOException { // read a 4-figure table from file if (something_wrong_during_input) throw new IOException(); else ... return answer; }

  10. Detecting Exceptions • In the previous example, main() will be puzzled on receiving the IOException object from tan(). • What should we do in the message sender? • We have to define a try block in the message sender to detect exceptions. … void main(…) { double value = tan(30); }

  11. Try Block • From the signature of tan(), we know that sending this message is risky. double tan(double angle) throws IOException { … } … void main(…) { double value; try { value = tan(30); value = value * 3.14159; } }

  12. Try Block • In case of receiving any exceptions from any statements in the try block, the rest (subsequent) statements in the try block will be skipped. double tan(double angle) throws IOException { … throw new IOException(); } … void main(…) { double value; try { value = tan(30); value = value * 3.14159; // wow wow, skipped } }

  13. Limited Liability • Skipping the remaining statements in the try block means saving the method from dying! • It avoids skipping the rest statements in the whole method body! i.e. rescuing the method. … void main(…) { double value; try { value = tan(30); value = value * 3.14159; // wow wow, skipped } double result = value + 19 * 97 - 2002; } Something is missing here… See next slide...

  14. Twins: Detection and Handling • In fact, try and catch are twins. • Try is responsible for detection. • Catch is responsible for identification and handling.

  15. Handling Exceptions double tan(double angle) throws IOException { if (read_4_figure_table_error) throw new IOException(); … } … void main(…) { double value; try { value = tan(30); value = value * 3.14159; // wow wow, skipped … } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); value = 3.14159; } // the program continues normally hereafter }

  16. Handling Exceptions • We catch certain type of exception by: catch (ExceptionType an_object_reference) { statements to remedy the condition; } // resume normal execution hereafter • an_object_reference lets us access the fields/methods of the exception object. • Thus further information may be passed from the exception thrower to the exception handler through the exception object.

  17. Catching Several Kinds of Possible Exceptions double tan(double angle) throws IOException, ArithmeticException { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new ArithmeticException(); } … void main(…) { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3.14159; // wow wow, skipped } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); value = 3.14159; } catch (ArithmeticException arithmetic_exception_object_ref) { System.out.println(“Arithmetic Exception received!”); value = 0.0; } // the program continues normally hereafter }

  18. Exception Propagation • Unless encountering a try-catch block which handles the received exception, the exception will cause termination of the current method. • In such case, the method re-throws (propagates) the same exception object to its message sender. • The involved method should therefore declare that it may throw that exception in its method signature.

  19. Exception Propagation double tan(double angle) throws IOException, ArithmeticException { if (read_4_figure_table_error) throw new IOException(); if (angle == 90) throw new ArithmeticException(); } … void main(…) throws ArithmeticException { double value; try { value = tan(90); // tan 90 = infinity! value = value * 3.14159; // wow wow, skipped } catch (IOException io_exception_object_ref) { System.out.println(“Input Output Exception received!”); System.out.println(“We have handled it gracefully!”); value = 3.14159; } // ArithmeticException is not caught // this method terminates and propagates the arithmetic exception object // on receiving ArithmeticException }

  20. Top-Level Boss • The Java Virtual Machine is the first message sender which sends a message to main(). • It is thus the ultimate receiver of any un-handled exceptions. • The exception propagation stops either on: • Reaching a try-catch block which handles the exception. • Or reaching the JVM and causing program termination.

  21. Array • Popular and important data structure • use an index to access variables of the same name (identifier) and type: i[0] = 5; i[654] = -378; • How to do that? int[] i = new int[1000]; • OR( C++ style ) int i[] = new int[1000];

  22. Declaration and Array Creation int[] i = new int[1000]; is equivalent to int[] i; // i is nothing yet i = new int[1000]; // i keeps something

  23. Another Form of Array Creation • By enumerating its initial values: char[] vowels = {'a', 'e', 'i', 'o', 'u'}; • Then vowels is an array of 5 char variables with vowels[0]  'a' vowels[1]  'e' vowels[2]  'i' vowels[3]  'o' vowels[4]  'u' • Array index must be an integer: [0 to length – 1]. There are 5 char variables!

  24. Syntax of Creating Arrays type[] array_name = new type[length]; type[] array_name = {value1, value2, ...}; e.g. double[] GPA = new double[50]; String[] countryCode = new String[175]; String address[] = new String[30]; char[] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; • type may be primitive type, class type or even an other array type.

  25. Properties of Array • A bounded (fixed length) and indexed collection of elements of the same type. • Array length is fixed at the time of creation. • Element access is done using an index [ ]. • vowels[0] to vowels[vowels.length – 1] • vowels[-8]  ArrayIndexOutOfBoundsException • To get the length (size) of an array: • vowels.length • NOT vowel.length() [confused with String]

  26. Example: The Parameter in main() class TestArgs { public static void main(String[] args) { System.out.println("There are " + args.length + " arguments:"); int i; for (i = 0; i < args.length; i++) System.out.println( args[i] ); } } C:\LetSee\> java TestArgs There are 0 arguments: C:\LetSee\> java TestArgs Apple Orange There are 2 arguments: Apple Orange

  27. Example: The Parameter in main() • A Java application program can receive some parameters at start-up. • These start-up parameters are called command-line arguments. • The main() method is the receiver of such arguments. • Such arguments are stored in a String array created by the JVM. • JVM sends a message to main() with such an array.

  28. Array of Object References int[] i; // a null integer array reference i = new int[100]; // create a new integer array i[5] = 87; // let i refer to the array // initially, i[0] = … = i[99] = 0 Octopus[] deck; // a null Octopus array reference deck = new Octopus[10]; // initially, deck[0] = … = null deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); • Creating a new array  Creating members

  29. Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) ?

  30. Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) ? ? ? deck[2] (reference) deck[1] (reference) deck[0] (reference)

  31. Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); ? ? deck[ ] (reference) Octopus (class) Octopus (object) deck[2] (reference) deck[1] (reference) deck[0] (reference)

  32. Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) ? Octopus (class) Octopus (object) deck[2] (reference) deck[1] (reference) deck[0] (reference)

  33. Array Itself is Also a Reference Octopus[] deck; deck = new Octopus[3]; deck[0] = new Octopus(); deck[1] = deck[0]; deck[2] = new Octopus(); deck[ ] (reference) Octopus (object) Octopus (class) Octopus (object) deck[2] (reference) deck[1] (reference) deck[0] (reference) Class type array

  34. Array Itself is Also a Reference int[] i; i = new int[3]; i[0] = 7; i[1] = i[0]; i[2] = 9; i[ ] (reference) i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 Primitive type array  Class type array

  35. Assignment of the Whole Array int[] i = new int[3]; int[] j; j = i; // object reference copying j[2] = 9; // i[2] = 9 i[1] = 7; // j[2] = 7 j[0] = 7; // i[0] = 7 i[ ] (reference) They refer to the same array! i[2] (int) 9 i[1] (int) 7 i[0] (int) 7 j[ ] (reference)

  36. Assignment of the Whole Array int[] i = new int[3]; int[] j; j = new int[5]; i[ ] (reference) OR, Create another one! i[2] (int) 9 i[1] (int) 7 j[ ] (reference) i[0] (int) 7 j[4] (int) 0 j[3] (int) 0 j[2] (int) 0 j[1] (int) 0 j[0] (int) 0

  37. Assignment of the Whole Array int[] i = new int[3]; int[] j; j = new int[5]; j = i; i[ ] (reference) Remember to Keep It Well! i[2] (int) 9 i[1] (int) 7 j[ ] (reference) i[0] (int) 7 j[4] (int) 0 j[3] (int) 0 Killed j[2] (int) 0 j[1] (int) 0 j[0] (int) 0

  38. GPAs[1] 4.0 GPAs[0] 4.0 New Concept: Primitive Type Array Argument Passing class Student { public static void studyHard(double[] newGPAs) { newGPAs[0] = 4.0; newGPAs[1] = 4.0; } public static void main(String[] args) { double[] GPAs = new double[2]; GPAs[0] = 1.0; GPAs[1] = 1.5; Student.studyHard(GPAs); System.out.println(GPAs[0]); System.out.println(GPAs[1]); } } newGPAs (Reference) Start here  GPAs[1] 1.5 GPAs[0] 1.0 GPAs (Reference) Copy array reference to formal parameter when sending message. Change to the formal parameter DOES NOT affect actual parameter!

  39. Employee (object) Employee (object) Employee (object) salary 1000 salary 2000 salary 5000 New Concept: Object Type Array Argument Passing class CUHK { public static void fire(Employee[]victims) { for (int i = 0; i < victims.length; i++) victims[i].salary = 0; } public static void main(String[] args) { Employee[] TAs = new Employee[3]; TAs[0] = new Employee(1000); TAs[1] = new Employee(2000); TAs[2] = new Employee(5000); CUHK.fire(TAs); } } class Employee { public int salary; public Employee(int initialSalary) { salary = initialSalary; } } victims (reference) Start here  TAs[0] (reference) TAs (reference) TAs[1] (reference) TAs[2] (reference)

  40. Table (2-Level Array) What’s the type? double // There are 176 students, 8 assignments // record their marks in double double[][] mark = new double[176][8]; mark[6][0] = 99.34; // mark: 7th student, Asg1 mark[175][6] = 89.12; // mark: last student, Asg7 double[] singleStudent; singleStudent = mark[175]; // refer to the singleStudent[6] = 45.67; // marks of the last one System.out.println(mark[175][6]); // would print 45.67 • Elements of an array could be arrays. • Array reference of array references. double[]

  41. Table Illustrated mark[ ][ ] (reference) mark[2] (reference) mark[1] (reference) mark[0] (reference) mark[2][3] (double) 9.45 mark[1][3] (double) 8.48 mark[0][3] (double) 9.11 mark[2][2] (double) 2.49 mark[1][2] (double) 3.40 mark[0][2] (double) 1.42 Array of Array of double mark[2][1] (double) 3.43 mark[1][1] (double) 6.13 mark[0][1] (double) 5.43 mark[2][0] (double) 1.75 mark[1][0] (double) 1.15 mark[0][0] (double) 0.35

  42. Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 i[1] (int) 7 i[0] (int) 7

  43. Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 i[1] (int) 7 j[ ] (reference) i[0] (int) 7 ?

  44. Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 i[1] (int) 7 j[ ] (reference) i[0] (int) 7 j[2] (int) 0 j[1] (int) 0 j[0] (int) 0

  45. Duplicating an int Array int[] i = {7, 7, 9}; int[] j; j = new int[i.length]; for (int count = 0; count < i.length; count++) j[count] = i[count]; i[ ] (reference) Copy the elements one-by-one i[2] (int) 9 i[1] (int) 7 j[ ] (reference) i[0] (int) 7 j[2] (int) 9 j[1] (int) 7 j[0] (int) 7

  46. Duplicating an Object Array Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; deck[ ] (reference) Octopus (object) Octopus (class) Octopus (object) deck[2] (reference) deck[1] (reference) deck[0] (reference)

  47. Duplicating an Object Array Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; newDeck[ ] (reference) deck[ ] (reference) Octopus (object) Octopus (class) Octopus (object) ? deck[2] (reference) deck[1] (reference) deck[0] (reference)

  48. Duplicating an Object Array Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; newDeck[ ] (reference) deck[ ] (reference) Octopus (object) Octopus (class) Octopus (object) newDeck[2] (reference) deck[2] (reference) newDeck[1] (reference) deck[1] (reference) newDeck[0] (reference) deck[0] (reference)

  49. Duplicating an Object Array Octopus[] deck; ... Octopus[] newDeck; newDeck = new Octopus[deck.length]; for (int count = 0; count < deck.length; count++) newDeck[count] = deck[count]; newDeck[ ] (reference) deck[ ] (reference) Octopus (object) Octopus (class) Octopus (object) Only the object references are copied! newDeck[2] (reference) deck[2] (reference) newDeck[1] (reference) deck[1] (reference) newDeck[0] (reference) deck[0] (reference)

  50. 7-Minute Break

More Related