Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java the UML Way versjon 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and.

Similar presentations


Presentation on theme: "Java the UML Way versjon 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and."— Presentation transcript:

1 Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8 Java Libraries and Exception Handling Using the Java APIpage 2 Using the on-line documentationpage 3-6 Packagespage 7-8 The myLibrary packagepage 9 Localizationpage 10 Printing decimal numeralspage Excaptions, in generalpage Exception objectspage 16-24

2 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 2 Using the Java API Examples of classes in the Java API: –java.lang.String: managing texts –java.swing.JApplet: creating applets –java.awt.Component, java.awt.Graphis, java.awt.Color, java.awt.Font: creating graphics There are many more classes! An important part of programming Java is to know how to use these classes. You should get accustomed to use these classes without understanding all the details. You should get accustomed to use the documentation describing these classes. Only a very few classes, and a few methods in every class, is described in this book. It's better using the online documentation!

3 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 3 The Online API Documentation The documentation should be downloaded from Sun's web site and installed in the jdk1.4-directory. The documentation consists of a lot of html files, which you navigate through using an ordinary browser. Here is the index page:

4 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 4 A Couple of Clicks Further…

5 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 5 the relationship between the String class and other classes here you may switch to another class index showing all public methods and variables in all classes

6 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 6 The String Class, the continuation... The String Class, still more…you have to try it yourself!

7 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 7 Why Using Packages Every class belongs to a package All classes in the API belong to named packages, e.g. javax.swing and java.applet Our example programs usually belong to unnamed packages However, we should put classes we make, which we believe will be generally useful to us or to others, into named packages. –The advantage to this is that we don’t need to copy the classes when we use them in different directories. –Thus, we also avoid maintaining multiple copies of these classes. Is it possible to construct globally unambiguous class names? Yes, you can be reasonably sure that the class name is unambiguous if you let the class belong to a package named with the URL of the company’s home page on the Internet.

8 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 8 An Example: The Package Structure for Classes from the XSSoft Company com xssoft graphicsdatabases Circle.class Polygon.class Person.class RealEstate.class c: java C LASSPATH=.;C:\java import com.xssoft.graphics.Circle;

9 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 9 The myLibrary Package Contains some utility classes from the book What have to be done with a class to be part of a package? Example, from chapter 6: import javax.swing.JOptionPane; class InputReader { … This class is inserted into the myLibrary package: package myLibrary; import javax.swing.JOptionPane; public class InputReader {

10 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 10 Localization By formatting, we mean how, for example, a number is displayed on the screen. Formatting doesn’t affect the value itself. Assume the variable number contains the value The numerical value can be output (formatted) in several ways: –35,645.4 English/American locale –35 645,4Some European locale –35 645,40 Some European locale –35645Likely to be anyone Formatting decimal numerals are a mere fragment of what is called localization. This refers, for example, to currency units, date formats, alphabet sort orders, and also—of course—language. In Windows this is called "Regional settings". We can choose to let our Java program follow the regional settings, or we may specify a special location (language and country). The java.util.Locale class helps us: Locale german = new Locale("de", "DE"); Locale.setDefault(german); Not all classes take location into account. Here is a statement that does not: System.out.println(number);

11 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 11 Printing Decimal Numerals We use the java.text.DecimalFormat class An example: Locale locc = new Locale("en", "US"); Locale.setDefault(locc); DecimalFormat theFormat = new DecimalFormat("###0.00"); String text = theFormat.format(13.4); System.out.println(text); text = theFormat.format( ); System.out.println(text); gives the output The format consists of codes, one for each position: 0 - Always print a digit here. # - Print a digit here, but not if this digit is a leading or trailing zero.. - The position of the decimal separator. At least one digit to the left of the decimal separator, and always exactly two digits to the right of it.

12 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 12 Printing Numbers Out in Columns An example: None of the codes will insert blank spaces if there are leading zeroes at the beginning of the number. The myLibrary.MyDecimalFormat may be used to create the output as above: myLibrary.MyDecimalFormat format1 = new myLibrary.MyDecimalFormat(5, 2); double aNumber = 8.5; for (int i = 0; i < 8; i++) { System.out.println(format1.format(aNumber)); aNumber *= 10; } number of positions before decimal separator, leading zeroes are replaced by spaces no. of digits after decimal separator

13 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 13 Exceptions, a General Approach An exception is a state that can arise during runtime, but which is a deviation from normal. Examples: –The program tries to divide by zero, find the square root or logarithm of a negative number, or some other mathematical “impossibility”. –The program tries to get a character in an invalid position in a string. For example: in the “Example” string, 0, 1, 2, 3,..., 6 are valid positions, but position 7 is not. –A number falls outside some valid interval. The program has to handle the exception states that arise during runtime in a sensible manner. From chapter 6 we have an example of controlling input data: String text = JOptionPane.showInputDialog(prompt); while (text == null || text.trim().equals("")) { JOptionPane.showMessageDialog(null, "You have to enter data!"); text = JOptionPane.showInputDialog(prompt); }

14 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 14 What if a Server Objects doesn't Manage Its Task? A client sends a message to a server object. If things went wrong, the server object should usually not take the error handling in its own hands, by for example printing an error message to the screen. A message should be sent back to the client, for example: –return a value outside the valid range of values –return false if no other data should be returned In this way the client gets the responsibility to decide what's next. The Grade class to the right is an example. Here is the client: class Grade { private int points; public Grade(int initPoints) { points = initPoints; } public char getGrade() { // returns an 'X' if // too many point, a 'Z' if too few points if (points > 100) return 'X'; else if (points >= 90) return 'A'; else if (points >= 80) return 'B'; else if (points >= 70) return 'C'; else if (points >= 60) return 'D'; else if (points >= 0) return 'F'; else return 'Z'; } Grade theGrade = new Grade(points); char grade = theGrade.getGrade(); if (grade == 'Z') { JOptionPane.showMessageDialog(null, "Negative number of points not allowed."); } else if (grade == 'X') { JOptionPane.showMessageDialog(null, "Max. number of points is 100"); } else { JOptionPane.showMessageDialog(null, points + " points gives the grade " + grade); }

15 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 15 Why isn't this Method Good Enough? 1.What if all possible characters were valid return values from the getGrade() method? 2.Sometimes this sort of exception handling is rather bothersome. –An example: A program reads data from a file. Errors may occur every time the program contacts the file: establish a connection to the file if this was successful read a little data from the file while this was successful and there is more data read data from the file end the connection to the file

16 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 16 Exceptions A Java exception is an object that contains information about the error. If something goes wrong inside a method, the method throws an exception object. This object doesn’t come through the return value from the method. The client can catch this object or throw it without handling it. Now the program outline from before will look like this: try establish a connection to the file (exception object may be thrown) read a little data from the file (exception object may be thrown) while there is more data read a little data from the file (exception object may be thrown) end the connection to the file (exception object may be thrown) catch any exception object common error handling try – throw - catch

17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 17 main() Catches an Exception Object That is Generated in the getData() Method public static void main() { try { …statements… fileObject.getData(); … statements... } catch (Exception e) {..do something relevant, the e parameter is a reference to the object containing information about the error... } public …. getData() throws Exception { … statements... if exceptional condition throw new Exception … statements... } an object is instantiated, it’ll contain information about the exception

18 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 18 methodX() Receives an Exception Object from getData(), Which It Sends on to main()

19 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 19 Exception Handling for Beginners If the compiler says that the exception has to be caught or thrown onwards, it’s easiest to throw it onward. Write throws Exception in the method head. If that doesn’t work (for example, in the init() method in an applet), enclose the block that contains the problematic method with try and catch. If the exception causes the program to stop when it’s running, you should try to change the program to avoid that happening (see next slide). The online API documentation covers all the exceptions a method can throw.

20 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 20 Exceptions That Should not Occur in a Program These are subclasses of RunTimeException Examples –ArithmeticException is thrown if we try integer division by zero Avoid it by a simple test: –if (denominator != 0)… –NullPointerException is thrown if we're trying to use a reference before it's set to point to an object: Be careful to check that all references point to objects. –StringIndexOutOfBoundsException is thrown by charAt() in the String class if invalid argument. Avoid it by a simple test: –if (pos >= 0 && pos < text.length())…. Solve the problem, page 226.

21 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 21 Three Different Types of Exceptions

22 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 22 Catching or Throwing an Exception? Example: class MaintainNameArchive { public static void main(String[] args) throws Exception {...file handling... } Or we may write: class MaintainNameArchive { public static void main(String[] args) { try {...file handling... } catch (Exception e) { System.out.println("Program aborted: " + e); } The main() method should catch all exceptions to avoid “ugly” messages on the screen and program abortions. (In simple examples and test programs, of course, this is less important.) Other methods should only catch exceptions that can be handled reasonably. Otherwise the exceptions should be thrown on so that the client can handle them.

23 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 23 Handling Different Exceptions in Different Ways public static void main(String[] args) { // program listing 11.2 String filename = "numberFile.txt"; try {...establish connection to the file... int sum = 0; try {...read text from the file......convert the text into number, and update sum... } catch (IOException e) { System.out.println("IO-Error when reading from file: " + filename); } catch (NumberFormatException e) { System.out.println("Error when converting from text to number."); }...close the file......print the sum... } catch (FileNotFoundException e) { System.out.println("File not found: " + filename); } catch (IOException e) { // all other IO errors are caught here System.out.println("IO-Error when opening/closing the file: " + filename); }

24 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 24 The try Statement, More Examples public ArrayList getAll() throws SQLException { // program listing some initializations... try {...search through the database, exceptions may be thrown out of this method... } finally { // the statements below are executed regardless of exceptions thrown...release database resources, in every case, also if exceptions are thrown... } public static void main(String[] args) throws Exception { String filename = "numberFile.txt"; try {...establish connection to the file......read text from the file... } catch (FileNotFoundException e) { System.out.println("File not found: " + filename); }

25 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 25 To Create and Throw an Exception Object public char charAt(int index) { // from the java.lang.String class if ((index = count)) { throw new StringIndexOutOfBoundsException(index); } return value[index + offset]; } try { number = InputReader.inputInteger("Enter an integer: "); if (number limitNo2) throw new NumberFormatException(); } catch (NumberFormatException e) { System.out.println("Invalid number."); // or something else } Show program listing 8.2 page 233.

26 Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 8, page 26 To Create and Use Your Own Exception Class class InvalidEmployeeException extends Exception { public InvalidEmployeeException() { super("Invalid employee data"); } public InvalidEmployeeException(String message) { super(message); } public Employee(int initNumber, String initName, int initSalary) throws InvalidEmployeeException { if (initSalary < limitSal) { throw new InvalidEmployeeException("Salary: " + initSalary + "\nThe salary should be at least $" + limitSal); } else if (initNumber limitNo2) { throw new InvalidEmployeeException("Number: " + initNumber + "\nThe number should be in the interval [" + limitNo1 + ", " + limitNo2 + "]."); } else { number = initNumber; name = initName; salary = initSalary; } // And in the client program: try {..... } catch (InvalidEmployeeException e) {.....


Download ppt "Java the UML Way versjon 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and."

Similar presentations


Ads by Google