Transcript PPT3

Exception Handling
&
Collections
Covered Topics
•
•
•
•
Exception Definition
Exception Occurance
Exception handling
Exception Propagation
Definition
• An exception is any unusual event, either
erroneous or not, detectable by either hardware or
software, that may require special processing.
• The special processing that may be required after
the detection of an exception is called exception
handling
• The exception handling code unit is called an
exception handler
Advantages of exception handling
• Improves the reliability of the application
program
• Allows simple program code for exception
check and handling into source
Exceptions in Java
• All exceptions are instances of a class
extended from throwable class or its
subclass.
Object
Throwable
Error
...
Exception
RuntimeException
...
...
Definition of Exception
• Error Class
– Critical error which is not acceptable in normal
application program.
– Exceptions of type error are used by the java runtime
system to indicate errors having to do with the run-time
environment, itself e.g. stack overflow.
– Such errors are created in response to catastrophic
failures that can not usually be handled by the program.
• Exception Class
– Possible exception in normal application
program execution
– Possible to handle by programmer
System-Defined Exception
• Raised implicitly by system because of illegal
execution of program
• When cannot continue program execution any
more
• Created by Java System automatically
• Exception extended from Error class and
RuntimeException class
 [DivByZero.java]
System-Defined Exception
• IndexOutOfBoundsException :
– When beyond the bound of index in the object which use index,
such as array, string, and vector
• ArrayStoreException :
– When assign object of incorrect type to element of array
• NegativeArraySizeException :
– When using a negative size of array
• NullPointerException :
– When refer to object as a null pointer
• SecurityException :
– When violate security. Caused by security manager
• IllegalMonitorStateException :
– When the thread which is not owner of monitor involves wait or
notify method
Programmer-Defined Exception
Exceptions raised by programmer
• Check by compiler whether the exception
handler for exception occurred exists or not
– If there is no handler, it is error
• Sub class of Exception class
Exception Occurrence
• Raised implicitly by system
• Raised explicitly by programmer
Throwable class or
– throw
Statement
throw
ThrowableObject;
 [ThrowStatement.java]
its sub class
Exception Occurrence
class ThrowStatement extends Exception {
public static void exp(int ptr) {
if (ptr == 0)
throw new NullPointerException();
}
public static void main(String[] args) {
int i = 0;
ThrowStatement.exp(i);
}
}
java.lang.NullPointerException
at ThrowStatement.exp(ThrowStatement.java:4)
at ThrowStatement.main(ThrowStatement.java:8)
Exception Occurrence
• throws Statement
– When programmer-defined exception is raised,
if there is no exception handler, need to
describe it in the declaration part of method
[modifiers] returntype methodName(params) throws e1, ... ,ek { }
 [ThrowsClause.java]
Exception-list
throws :example
Class ThrowsDemo {
static void throwOne() {Throws IllegalAccessException {
System.out.println(“inside throwone”);
Throw new IllegalAccessException(“demo”);
}
Public static void main(String args[]){
try {
t hrowOne();
}
throwOne();
}catch(IllegalAccessException e) {
System.out.println(“caught : “ +e);
}
}
}
Exception Handling
• try-catch-finally Statement
– Check and Handle the Exception
try {
// …
} catch (ExceptionType1 identifier) {
// …
} catch (ExceptionType2 identifier) {
// …
} finally {
// …
}
 [ExceptionHandler.java]
Exception Handling
• Default Exception Handler
– When system-defined exception occurred, if
programmer does not deal with it, it would be
processed by default exception handler
– Simple function to output error message and exit
• Execution Order of Exception Handler
– Finally clause is executed independent of exception and
catch
 [SystemHandler.java] , [FinallyClause.java]
Exception Propagation
• Manage exceptions by collecting them in a specific
method to propagate the exceptions to calling
method
– To prevent scattering of exception handling
• Exception Propagation Order
– If there is no catch block to deal with the exception, it is
propagated to calling method
• All executions are ignored until finding the
exception handler
 [Propagate.java]
Exception Propagation
public class Propagate {
void orange() {
ArithmeticException Occurred
int m = 25, i = 0;
i = m / i;
}
void apple() {
orange();
}
public static void main(String[] args) {
Propagate p = new Propagate();
p.apple();
Output by Default Exception
}
Handler
}
java.lang.ArithmeticException:
/ by zero
at Propagate.orange(Propagate.java:4)
at Propagate.apple(Propagate.java:8)
at Propagate.main(Propagate.java:11)
Exception Propagation
• Explicit Description for possibility of Exception
Occurrence
– System-Defined Exception
• Do not need to announce the possibility of exception
occurrence
– Programmer-Defined Exception
• When it is not managed in correspond method, the exception
type should be informed.
• Use the throws clause
Exception Propagation
class MyException extends Exception { }
public class ClassA {
// …
public void methodA() throws MyException {
// …
if (someErrCondition())
throw new MyException();
// …
}
}
 [MsgException.java]
Inheritance of Exception
• If base-class method throws an exception,
derived-class method may throw that
exception or one derived from it.
• Derived-class method cannot throw an
exception that is not a type/subtype of an
exception thrown by the base-class method.
class Stolen extends CarException {}
class NoGasoline extends CarException {}
abstract class Car {
void stop() throws CarException { Cann’t throw
// ...
BadWeather,
throw new CarException();
NoSpecialGasoline
}
abstract void start() throws Stolen, NoGasoline;
}
class BadWeather extends CarException {}
class NoSpecialGasoline extends NoGasoline {}
public class SportsCar extends Car {
void stop() throws BadWeather { /* … */ }
void start() throws NoSpecialGasoline{ /* ... */}
public static void main(String args[]) {
SportsCar sc = new SportsCar();
try {
sc.start();
} catch(NoSpecialGasoline e) { }
}
}
Collections
Collections : Introduction
• A collections framework is a unified architecture for
representing and manipulating collections. All collections
frameworks contain the following:
– Interfaces: These are abstract data types that represent collections.
– Implementations: These are the concrete implementations of the
collection interfaces. In essence, they are reusable data structures.
– Algorithms: These are the methods that perform useful
computations, such as searching and sorting, on objects that
implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many
different implementations of the appropriate collection interface. In
essence, algorithms are reusable functionality.
Collections in Java
• The java collection framework standardizes the way in
which groups of objects are handled by a program.
• Manipulate grouped data as a single object
– Java provides List, Set, Map
– Methods include : add, contains, remove, size, loop over, sort,
…
• Insulate programmer from implementation
– array, linked list, hash table, balanced binary tree
•
•
•
•
•
•
Like C++ Standard Template Library (STL)
Can grow as necessary
Contain only Objects (reference types)
Heterogeneous
Can be made thread safe (simultaneous access)
Can be made unmodifiable
Advantages of using Collections
• Reduce programming effort
• Increase program speed and quality
• Allows interoperability among unrelated
APIs
• Reduce effort to learn and to use new APIs
• Reduce effort to design new APIs
• Foster software resuse
Interfaces
•
List
• It is an ordered collection that can contain duplicate elements
(a.k.a. sequence)
• Like an array
– elements have positions indexed 0…size( )-1
– duplicate entries possible
• Unlike an array
–
–
–
–
can grow as needed
can contain only Objects (heterogeneous)
easy to add/delete at any position
API independent of implementation
(ArrayList, LinkedList)
• Implemented via interface List
– ArrayList
– LinkedList
– Vector
Import java.util.*;
Class LinkedListDemo{
public static void main(String args[]) {
LinkedList[] ll=new LinkedList();
ll.add(“F”);ll.add(“B”); ll.add(“D”);ll.add(“E”);
ll.addLast(“Z”);
ll.addFirst(“A”);
ll.add(1,”A2”);
System.out.println(“original contents of ll : “, ll);
ll.remove(“F”);
ll.removeFirst(); ll.removeLast();
System.out.println(“ll after deleting first and last :”, ll);
Object val=ll.get(2);
ll.set(2,(String)val + “changed”);
System.out.println(“ll after changing : “, ll);
}
}
Output:
Original contents of ll:[A,A2,F,B,D,E,C,Z]
ll after deleting first and last : [A2,B,D,E,C]
ll after changing : [ A2,B,D changed, E,C]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 22.3: CollectionTest.java
// Using the Collection interface.
import java.awt.Color;
import java.util.*;
public class CollectionTest {
private static final String colors[] = { "red", "white", "blue" };
// create ArrayList, add objects to it and manipulate it
public CollectionTest()
{
List list = new ArrayList();
// add objects to list
list.add( Color.MAGENTA );
// add a color object
for ( int count = 0; count < colors.length; count++ )
list.add( colors[ count ] );
list.add( Color.CYAN );
// add a color object
Use List method add to
add objects to ArrayList
// output list contents
System.out.println( "\nArrayList: " );
for ( int count = 0; count < list.size(); count++ )
System.out.print( list.get( count ) + " " );
List method get returns
individual element in List
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Method removeStrings takes a
Collection as an argument; Line 31
passes List, which extends
Collection, to this method
// remove all String objects
removeStrings( list );
// output list contents
System.out.println( "\n\nArrayList after calling removeStrings: " );
for ( int count = 0; count < list.size(); count++ )
System.out.print( list.get( count ) + " " );
} // end constructor CollectionTest
// remove String objects from Collection
private void removeStrings( Collection collection )
{
Iterator iterator = collection.iterator(); // get iterator
// loop while collection has items
while ( iterator.hasNext() )
if ( iterator.next() instanceof String )
iterator.remove(); // remove String object
}
Obtain Collection iterator
Iterator method hasNext
determines whether the Iterator
contains more elements
Iterator method next returns
next Object in Iterator
Use Iterator method remove to
remove String from Iterator
51
public static void main( String args[] )
52
{
53
new CollectionTest();
54
}
55
56 } // end class CollectionTest
ArrayList:
java.awt.Color[r=255,g=0,b=255] red white blue java.awt.Color
[r=0,g=255,b=255]
ArrayList after calling removeStrings:
java.awt.Color[r=255,g=0,b=255] java.awt.Color[r=0,g=255,b=255]
22.6 Algorithms
• Collections Framework provides set of algorithms
– Implemented as static methods
• List algorithms
–
–
–
–
–
–
sort
binarySearch
reverse
shuffle
fill
copy
• Collection algorithms
– min
– max
• Like a List
–
–
–
–
can grow as needed
can contain only Objects (heterogeneous)
easy to add/delete
API independent of implementation
• HashSet : stores elements in a hash table
• TreeSet :stores elements in a tree
• Unlike a List
– elements have no positions
– duplicate entries not allowed
Set
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// SetTest.java
// Using a HashSet to remove duplicates.
import java.util.*;
public class SetTest {
private static final String colors[] = { "red", "white", "blue",
"green", "gray", "orange", "tan", "white", "cyan",
"peach", "gray", "orange" };
// create and output ArrayList
public SetTest()
{
List list = new ArrayList( Arrays.asList( colors ) );
System.out.println( "ArrayList: " + list );
printNonDuplicates( list );
}
// create set from array to eliminate duplicates
private void printNonDuplicates( Collection collection )
{
// create a HashSet and obtain its iterator
Set set = new HashSet( collection );
Iterator iterator = set.iterator();
System.out.println( "\nNonduplicates are: " );
Create HashSet from
Collection object
Map
• A map is an object that stores associations
between keys and values, or key/value
pairs.
– Given a key, you can find its value.
– The keys must be unique,but the values may be
duplicated
– API syntax independent of implementation
(HashMap, TreeMap)
– Iterators for keys, values, (key, value) pairs
•
1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// WordTypeCount.java
// Program counts the number of occurrences of each word in a string
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class WordTypeCount extends JFrame {
private JTextArea inputField;
private JLabel prompt;
private JTextArea display;
private JButton goButton;
private Map map;
public WordTypeCount()
{
super( "Word Type Count" );
inputField = new JTextArea( 3, 20 );
map = new HashMap();
goButton = new JButton( "Go" );
goButton.addActionListener(
Create HashMap
Iterator Interface
// suppose Collection of Programmer objects
Iterator iter = engineers.iterator();
while (iter.hasNext()) {
Programmer p = (Programmer)iter.next();
p.feed("pizza");
}
• Note cast (Programmer) since Collection and
Iterator manage anonymous objects
• When collection has a natural ordering, Iterator will
respect it
• Supports safe remove() of most recent next
The collection algorithms
• Collections Framework provides set of algorithms
– Implemented as static methods
• List algorithms
–
–
–
–
–
–
sort
binarySearch
reverse
shuffle
fill
copy
• Collection algorithms
– min
– max