exception handling & collections. covered topics exception definition exception occurance...

40
Exception Handling & Collections

Upload: clifford-erik-watson

Post on 17-Jan-2016

292 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Exception Handling

&

Collections

Page 2: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Covered Topics

• Exception Definition

• Exception Occurance

• Exception handling

• Exception Propagation

Page 3: 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

Page 4: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Advantages of exception handling

• Improves the reliability of the application program

• Allows simple program code for exception check and handling into source

Page 5: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Exceptions in Java

• All exceptions are instances of a class extended from throwable class or its subclass.

ObjectObject

ThrowableThrowable

ErrorError ExceptionException

RuntimeExceptionRuntimeException

...

... ...

Page 6: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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.

Page 7: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

• Exception Class– Possible exception in normal application

program execution – Possible to handle by programmer

Page 8: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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]

Page 9: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 10: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 11: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Exception Occurrence

• Raised implicitly by system

• Raised explicitly by programmer – throw Statement

[ThrowStatement.java]

throw ThrowableObject; throw ThrowableObject;

Throwable class orits sub class

Throwable class orits sub class

Page 12: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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); } }

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)

java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8)

Page 13: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

[ThrowsClause.java]

[modifiers] returntype methodName(params) throws e1, ... ,ek { } [modifiers] returntype methodName(params) throws e1, ... ,ek { }

Exception-list

Page 14: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

throws :example

Class ThrowsDemo { static void throwOne() {

System.out.println(“inside throwone”);Throw new

IllegalAccessException(“demo”);}

Public static void main(String args[]){ t hrowOne();}

try {

throwOne();

}catch(IllegalAccessException e) {

System.out.println(“caught : “ +e);

}

}

}

Throws IllegalAccessException {

Page 15: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Exception Handling• try-catch-finally Statement

– Check and Handle the Exception

[ExceptionHandler.java]

try { // … } catch (ExceptionType1 identifier) { // … } catch (ExceptionType2 identifier) { // … } finally { // … }

try { // … } catch (ExceptionType1 identifier) { // … } catch (ExceptionType2 identifier) { // … } finally { // … }

Page 16: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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]

Page 17: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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]

Page 18: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Exception Propagation

public class Propagate { void orange() { int m = 25, i = 0; i = m / i; } void apple() { orange(); } public static void main(String[] args) { Propagate p = new Propagate(); p.apple(); } }

public class Propagate { void orange() { 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 ExceptionHandler

Output by Default ExceptionHandler

ArithmeticException OccurredArithmeticException Occurred

java.lang.ArithmeticException: / by zeroat Propagate.orange(Propagate.java:4)at Propagate.apple(Propagate.java:8)at Propagate.main(Propagate.java:11)

java.lang.ArithmeticException: / by zeroat Propagate.orange(Propagate.java:4)at Propagate.apple(Propagate.java:8)at Propagate.main(Propagate.java:11)

Page 19: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 20: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Exception Propagation

[MsgException.java]

class MyException extends Exception { } public class ClassA { // … public void methodA() throws MyException { // … if (someErrCondition()) throw new MyException(); // … } }

class MyException extends Exception { } public class ClassA { // … public void methodA() throws MyException { // … if (someErrCondition()) throw new MyException(); // … } }

Page 21: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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.

Page 22: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

class Stolen extends CarException {}class NoGasoline extends CarException {}abstract class Car {

void stop() throws CarException {// ...throw new CarException();}

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) { }}

}

Cann’t throw BadWeather, NoSpecialGasoline

Page 23: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Collections

Page 24: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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.

Page 25: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 26: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 27: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Interfaces

Page 28: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 29: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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]

Page 30: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

1 // Fig. 22.3: CollectionTest.java

2 // Using the Collection interface.

3 import java.awt.Color;

4 import java.util.*;

5

6 public class CollectionTest {

7 private static final String colors[] = { "red", "white", "blue" };

8

9 // create ArrayList, add objects to it and manipulate it

10 public CollectionTest()

11 {

12 List list = new ArrayList();

13

14 // add objects to list

15 list.add( Color.MAGENTA ); // add a color object

16

17 for ( int count = 0; count < colors.length; count++ )

18 list.add( colors[ count ] );

19

20 list.add( Color.CYAN ); // add a color object

21

22 // output list contents

23 System.out.println( "\nArrayList: " );

24

25 for ( int count = 0; count < list.size(); count++ )

26 System.out.print( list.get( count ) + " " );

27

Use List method add to add objects to ArrayList

List method get returns individual element in List

Page 31: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

28 // remove all String objects

29 removeStrings( list );

30

31 // output list contents

32 System.out.println( "\n\nArrayList after calling removeStrings: " );

33

34 for ( int count = 0; count < list.size(); count++ )

35 System.out.print( list.get( count ) + " " );

36

37 } // end constructor CollectionTest

38

39 // remove String objects from Collection

40 private void removeStrings( Collection collection )

41 {

42 Iterator iterator = collection.iterator(); // get iterator

43

44 // loop while collection has items

45 while ( iterator.hasNext() )

46

47 if ( iterator.next() instanceof String )

48 iterator.remove(); // remove String object

49 }

50

Obtain Collection iterator

Iterator method hasNext determines whether the Iterator

contains more elements

Use Iterator method remove to remove String from Iterator

Iterator method next returns next Object in Iterator

Method removeStrings takes a Collection as an argument; Line 31

passes List, which extends Collection, to this method

Page 32: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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]

Page 33: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 34: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

Set• 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

Page 35: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

• 1 // SetTest.java

• 2 // Using a HashSet to remove duplicates.

• 3 import java.util.*;

• 4 • 5 public class SetTest {

• 6 private static final String colors[] = { "red", "white", "blue",

• 7 "green", "gray", "orange", "tan", "white", "cyan",

• 8 "peach", "gray", "orange" };

• 9 • 10 // create and output ArrayList

• 11 public SetTest()

• 12 {• 13 List list = new ArrayList( Arrays.asList( colors ) );

• 14 System.out.println( "ArrayList: " + list );

• 15 printNonDuplicates( list );

• 16 }• 17 • 18 // create set from array to eliminate duplicates

• 19 private void printNonDuplicates( Collection collection )

• 20 {• 21 // create a HashSet and obtain its iterator

• 22 Set set = new HashSet( collection );

• 23 Iterator iterator = set.iterator();

• 24 • 25 System.out.println( "\nNonduplicates are: " );

• 26

Create HashSet from Collection object

Page 36: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 37: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

• 1 // WordTypeCount.java

• 2 // Program counts the number of occurrences of each word in a string

• 3 import java.awt.*;

• 4 import java.awt.event.*;

• 5 import java.util.*;

• 6 import javax.swing.*;

• 7 • 8 public class WordTypeCount extends JFrame {

• 9 private JTextArea inputField;

• 10 private JLabel prompt;

• 11 private JTextArea display;

• 12 private JButton goButton;

• 13 • 14 private Map map;

• 15 • 16 public WordTypeCount()

• 17 {• 18 super( "Word Type Count" );

• 19 inputField = new JTextArea( 3, 20 );

• 20 • 21 map = new HashMap();

• 22 • 23 goButton = new JButton( "Go" );

• 24 goButton.addActionListener(

• 25

Create HashMap

Page 38: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation
Page 39: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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

Page 40: Exception Handling & Collections. Covered Topics Exception Definition Exception Occurance Exception handling Exception Propagation

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