Transcript Exceptions

Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Java Libraries and Exception Handling
Using the Java API
Using the on-line documentation
Packages
The myLibrary package
Localization
Printing decimal numerals
Excaptions, in general
Exception objects
versjon 2002-04-17
page 2
page 3-6
page 7-8
page 9
page 10
page 11-12
page 13-15
page 16-24
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8
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!
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 2
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:
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 3
A Couple of Clicks Further…
classes
packages
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 4
here you may switch
to another class
index showing all public
methods and variables in all classes
the relationship
between
the String class
and other classes
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 5
The String Class, the continuation...
The String Class, still more…you have to try it yourself!
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 6
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.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 7
An Example: The Package Structure for Classes
from the XSSoft Company
c:
CLASSPATH=.;C:\java
java
com
import com.xssoft.graphics.Circle;
xssoft
graphics
Circle.class
Polygon.class
databases
Person.class
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
RealEstate.class
Chapter 8, page 8
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 {
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 9
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 35645.4. The numerical value
can be output (formatted) in several ways:
–
–
–
–
•
•
•
•
35,645.4
35 645,4
35 645,40
35645
English/American locale
Some European locale
Some European locale
Likely 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);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 10
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(-3456789.4);
System.out.println(text);
•
gives the output
At least one digit to the left
of the decimal separator,
and always exactly two
digits to the right of it.
13.40
-3456789.40
• 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.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 11
Printing Numbers Out in Columns
• An example:
8.50
85.00
850.00
8500.00
85000.00
• 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;
no. of digits after
for (int i = 0; i < 8; i++) {
decimal separator
System.out.println(format1.format(aNumber));
number of positions
aNumber *= 10;
before decimal separator,
}
leading zeroes are replaced by spaces
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 12
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);
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 13
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);
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 14
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
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 15
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
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 16
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
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 17
1
methodX() Receives an Exception Object
from getData(), Which
It Sends on to main()
methodX() throws the
public ... methodX()
throws Exception {
…statements…
fileObject.getData();
… statements...
}
exception object onward
2
public …. getData() throws Exception {
… statements...
if exceptional condition throw new Exception
… statements...
}
3
4
public static void main() {
try {
…statements…
anObject.methodX();
… statements...
} catch (Exception e) {
.. do something relevant, the
e parameter is a reference to
the object containing information
about the error...
}
}
an object is instantiated,
it’ll contain information
about the exception
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 18
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.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 19
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.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 20
Three Different Types of Exceptions
Object
Throwable
3. These exceptions have
to be handled with try and
catch, or they should be
Exception
thrown out of the method
2. Internal errors,
nothing to do
Error
...
VirtualMachineError
...
IOException
SQLException
...
RuntimeException
1. Try to write the programs
so that these exceptions
don’t occur.
ArithmeticException
NullPointerException
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
...
Chapter 8, page 21
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.
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 22
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);
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 23
The try Statement, More Examples
public ArrayList getAll() throws SQLException { // program listing 20.2
...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);
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 24
To Create and Throw an Exception Object
public char charAt(int index) { // from the java.lang.String class
if ((index < 0) || (index >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index + offset];
}
try {
number = InputReader.inputInteger("Enter an integer: ");
if (number < limitNo1 || number > limitNo2) throw new NumberFormatException();
} catch (NumberFormatException e) {
System.out.println("Invalid number."); // or something else
}
Show program listing 8.2 page 233.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 25
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 < limitNo1 || initNumber > limitNo2) {
throw new InvalidEmployeeException("Number: " + initNumber +
"\nThe number should be in the interval [" + limitNo1 + ", " + limitNo2 + "].");
} else {
// And in the client program:
number = initNumber;
try {
name = initName;
.....
salary = initSalary;
} catch (InvalidEmployeeException e) {
}
.....
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 8, page 26