Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An...

65
Lecture 23: Interfaces; Event Programming CS 170, Section 000 24 November 2009 24 November 2009 11/12/2009 CS170, Section 000, Fall 2009 1

Transcript of Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An...

Page 1: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Lecture 23: Interfaces; Event Programming

CS 170, Section 000

24 November 200924 November 2009

11/12/2009 CS170, Section 000, Fall 2009 1

Page 2: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Lecture Plan

Homework 7 questions?

Multiple inheritance: interfaces (parts of ch. 11)Example Event programming (parts of ch 15)Example: Event programming (parts of ch. 15)

Exceptions (chapter 18)

CS170, Section 000, Fall 2009 2

Page 3: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Recall: Superclasses and Subclasses

GeometricObject1.javaCircle4.javaRectangle1.java

3

Page 4: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Abstract Classes and Abstract Methods

GeometricObject -color: String -fi lled: boolean

Abstract class GeometricObject.java

Ci l j-dateCreated: java.ut il.Date

#GeometricObject() +getColor(): String +setColor(color: String): void +isFilled (): boolean

The # sign indicates protected modifer

Circle.java

Rectangle.java

+isFilled (): boolean+setFilled(fi lled: boolean): void +getDateCreated(): java.uti l.Date +toString(): String +getArea(): double +getPerimeter(): doubleAbstract methods

M th d tA d tP i t idd i+getPerimeter(): double

Circle -radiu s: double

Rectangle -width: double

Methods getArea and getPerimeter are overridden in Circle and Rectangle. Overridden methods are generally omitted in the UML d iagram for subclasses.

+Circle() +Circle(radius: double) +getRadius(): double +setRadius(radius: double): void +getDiameter(): double

-height: double

+Rectangle() +Rectangle(width: double, heigh t: double) +getWid th(): double +setWidth(wid th: double): void

4

g () ( )+getHeight(): double +setHeight(height: doub le): void

Page 5: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Fruit Example Revisited

abstract class Fruit {// Data fields, constructors, and methods omitted here

}

class Apple extends Fruit {{public String howToEat() {

return "Apple: Make apple cider";}

}}

class Orange extends Fruit {public String howToEat() {public String howToEat() {

return "Orange: Make orange juice";}

}}

11/25/2009 CS170, Section 000, Fall 2009 5

Page 6: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

What if we want to inherit from multiple classes?multiple classes?

Example: Pluot (hybrid of plum and apricot)l Pl t d F it{class Plum extends Fruit{public void HowToEat(){ System.out.println(“Plum: Wash”);}

}class Apricot extends Fruit{class Apricot extends Fruit{public void HowToEat(){ System.out.println(“Apricot: Pit it”);}

}class Pluot extends Plum extends Apricot{class Pluot extends Plum, extends Apricot{//class code

}public static void main (String [] args){public static void main (String [] args){Pluot p = new Pluot();p.HowToEat(); //which HowToEat method will be called?

}}}

11/25/2009 CS170, Section 000, Fall 2009 6

Page 7: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Interfaces

• What is an interface?

h f f l?• Why is an interface useful?

• How do you define an interface?

• How do you use an interface?

7

Page 8: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

What is an interface?Why is an interface useful?Why is an interface useful?

• An interface is a class-like construct that contains only constants and abstract methodscontains only constants and abstract methods

• Interface is to specify behavior for objects– For example, we can specify that the objects are comparable,

edible, cloneable using appropriate interfaces such as Comparable, Edible, and Cloneable

• A class that implements an interface must implement all the abstract methodsp– For example, we can define Orange and Chicken classes that

implement Edible interface

8

Page 9: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Interface is a Special Class

• Like an abstract class, you cannot create an instance from an interface using the newinstance from an interface using the new operator

f l h• You can create an instance from a class that implements an interface

• You can use an interface as a data type for a variable, as the result of casting, and so on.

9

Page 10: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Define an Interface

public interface InterfaceName { constant declarations;method signatures;

}}

public interface Edible {

/** Describe how to eat */

public abstract String howToEat();

}

10

Page 11: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Fruit Example Revisited (2)public interface Edible {/** Describe how to eat */public abstract String howToEat();public abstract String howToEat();

}

abstract class Fruit implements Edible{// Data fields, constructors, and methods omitted here// , ,

}

class Apple extends Fruit {public String howToEat() {return "Apple: Make apple cider";

}}

class Chicken e tends Animal implements Edible {class Chicken extends Animal implements Edible {public String howToEat() {return "Chicken: Fry it";

}} T Edibl j

Edible.java

}

11/25/2009 CS170, Section 000, Fall 2009 11

TestEdible.java

Page 12: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Omitting Modifiers in Interfaces

– All data fields are public final static (constants) in an interfacean interface

– All methods are public abstract in an interface

public interface T1 { public static final int K = 1; public abstract void p();

Equivalent public interface T1 { int K = 1; void p(); }} }

12

Page 13: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

The Comparable Interface

// This interface is defined in

// java.lang package

package java.lang;

public interface Comparable {

public int compareTo(Object o);public int compareTo(Object o);

}

13

Page 14: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

String and Date Classes

• Many classes (e.g., String and Date) in the Java library implement Comparable to define alibrary implement Comparable to define a natural order for the objects

public class String extends Object implements Comparable { // class body omitted

}

public class Date extends Object implements Comparable { // class body omitted

}

14

Page 15: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Declaring Classes to Implement ComparableComparable

GeometricObject «interface»Notation:

Rectangle

GeometricObject «interface»java.lang.Comparable

+compareTo(o: Object): int

Notation: The interface name and the method names are italicized. The dashed lines and hollow triangles are used to point totriangles are used to point to the interface.

ComparableRectangle

ComparableRectangle rectangle1 = new ComparableRectangle(4, 5);

ComparableRectangle rectangle2 = new ComparableRectangle(3 6);ComparableRectangle rectangle2 = new ComparableRectangle(3, 6);

System.out.println(Max.max(rectangle1, rectangle2));

Card class implements Comparable!

15

Card class implements Comparable!

Page 16: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

The Cloneable Interfaces

– Marker Interface: An empty interface.

– A marker interface does not contain constants or methods. It is used to denote that a class possesses certain desirable properties. A class that implements the Cloneable interface is marked cloneable, and its objects can be cloned using the l () th d d fi d i th Obj t lclone() method defined in the Object class.

package java.lang;pac age ja a. a g;

public interface Cloneable {

}

16

Page 17: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Implementing Cloneable Interface

• Declare a custom class that implements the Cloneable interface

House

17

Page 18: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Shallow vs. Deep Copy

House house1 = new House(1, 1750.50);

House house2 = (House)house1 clone();House house2 = (House)house1.clone();

house1: House

id = 1 area 1750 50

1

Memory

1750 50area = 1750.50whenBuilt whenBuilt: Date

date object contents house2 = house1.clone()

1750.50reference

house1: House

id = 1 area = 1750.50 whenBuilt

1

Memory

1750.50f

18

whenBuilt reference

Page 19: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Caution: conflicting interfaces

– A class may implement two interfaces with conflict information (e g two same constantsconflict information (e.g., two same constants with different values or two methods with same signature but different return type)g yp )

– This type of errors will be detected by the compiler.

19

Page 20: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Review questions

• Which of the following is a correct interface?

A. interface A { void print() { }; }

B. abstract interface A { print(); }

b f { b d () { } }C. abstract interface A { abstract void print() { };}

D. interface A { void print();}

20

Page 21: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Using Interfaces for Event Programming

• Event programming

– the flow of the program is determined by user actions (mouse clicks, key presses) or messages from other programs.

• Componentsp– Event sources: user interface components or other sources that

generate the events

– Events: user actions or other events– Event listener: reactions on events

• Basic steps

D fi t li t i l t i t f– Define event listener - implements an interface called ActionListener which contains a method actionPerformed() for processing the event

– Register event listener with event sources

Page 22: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

The Role of Event Listeners• One way to visualize the role of a listener is to imagine that

you have access to one of Fred and George Weasley’s“Extendable Ears” from the Harry Potter seriesExtendable Ears from the Harry Potter series.

• Suppose that you wanted to use these magical listeners todetect events in the canvas shown at the bottom of the slide.All you need to do is send those ears into the room where,being magical, they can keep you informed on anything thatgoes on there, making it possible for you to respond.

ListenerExample

Page 23: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Event Types• Java events come in many different types. The event types

used in this book include the following:M t hi h h th li k th– Mouse events, which occur when the user moves or clicks the mouse

– Keyboard events, which occur when the user types on the keyboard– Action events, which occur in response to user-interface actions

• Each event type is associated with a set of methods thatspecify how listeners should respond. These methods aredefined in a listener interface for each event type.

• As an example, one of the methods in the mouse listenerinterface is mouseClicked. As you would expect, Java callsthat method when you click the mousethat method when you click the mouse.

• Listener methods like mouseClicked take a parameter thatcontains more information about the event. In the case of

li k d th t i i di timouseClicked, the argument is a MouseEvent indicatingthe location at which the click occurred.

Page 24: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Taste of Event-Driven Programmingg g

• The example displays two buttons in the frame. A message is displayed on the console

h b tt i li k dwhen a button is clicked. • It’s all about the interfaces!

• HandleEvent.java

24

Page 25: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Events

• An event can be defined as a type of signal to the program that something has happened.

• The event is generated by external user g yactions such as mouse movements, mouse clicks, and keystrokes, or by the operatingclicks, and keystrokes, or by the operating system or program activities, such as a timer

25

timer.

Page 26: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

The Delegation Model

source: SourceClass

User Action

Trigger an event XListener

+addXListener(listener: XListener)

Action

+handler(event: XEvent)

Register by invokingddXLi t (li t )

(a) A generic source component

listener: ListenerClass

source.addXListener(listener);( ) g p

with a generic listener

source: JButton

+addActionListener(listener: ActionListener) ActionListener

+actionPerformed(event: ActionEvent)

listener: CustomListenerClass

f

Register by invoking source.addActionListener(listener);(b) A JButton source component

with an ActionListener

26

Page 27: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Internal Function of a Source ComponentInternal Function of a Source Component

source: SourceClass source: JButton

+addXListener(XListener listener)

Keep it a listAn event is triggered

+addActionListener(ActionListener listener)

Keep it a listAn event is triggered

event: XEvent listener1 listener2 …

Invoke listener1.handler(event) li t 2 h dl ( t)

event: ActionEvent

listener1 listener2 …

Invoke listener1.actionPerformed(event)li t 2 ti P f d( t)

(a) Internal function of a generic source object

listenernlistener2.handler(event)… listenern.handler(event)

(b) Internal function of a JButton object

listenernlistener2.actionPerformed(event)… listenern.actionPerformed(event)

27

Page 28: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Chapter 18 Exception HandlingChapter 18 Exception Handling

28

Page 29: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Motivation

When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can

ti t t i t f ll ? Thi i thcontinue to run or terminate gracefully? This is the subject we will introduce in this chapter.

29

Page 30: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Exceptions

• exception = unusual situation

• here program cannot execute 'normally'

• with a more-or-less external cause

• not a program bug

• eg file not found• eg file not found

• connection with server lost

• out of memory

• broken Java machine

Page 31: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Exceptions

• Some methods are declared to 'throw' an exception• Compiler will insist code 'catches' checked exception• Code form -• try {• .. call of method that may throw ExceptionType• }• catch ( ExceptionType e)• {• .. code to deal with exception• }

Page 32: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Example try catch

FileReader fr = null;try {try {

fr= new FileReader("test.dat");}}

catch (FileNotFoundException fe) {{System.out.println("Cant find file");}

FileReader is in package java ioFileReader is in package java.ioNote declare fr outside try and initialiseElse compiler complains fr may not be initialised

Page 33: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Exception-Handling Example

Quotient Run

QuotientWithIf Run

QuotientWithException Run

33

Page 34: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Exception Advantages

QuotientWithMethod RunQuotientWithMethod Run

Now you see the advantages of using exception handling. It enables a method to throw an exception to its caller Without this capability a method mustto its caller. Without this capability, a method must handle the exception or terminate the program.

34

Page 35: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Exception Types

ClassNotFoundException

AWTException

IOException

Exception

ArithmeticException

NullPointerException

Throwable

RuntimeException

Object

NullPointerException

IndexOutOfBoundsException

Several more classes Ill lA tE ti

LinkageError Several more classes

IllegalArgumentException

Error

AWTError

VirtualMachineError

35

Several more classes

Page 36: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

System Errors

ClassNotFoundException

IOException

AWTException

IOException

Exception

ArithmeticException

NullPointerException

Throwable

RuntimeException

Object

IndexOutOfBoundsException

Several more classes IllegalArgumentException

LinkageError

VirtualMachineError

Several more classes System errors are thrown by JVM and represented in the Error class. The Error class describes internal system

Error

AWTError

S l l

describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the

36

Several more classesuser and trying to terminate the program gracefully.

Page 37: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Exceptions

ClassNotFoundExceptionException describes errors caused by your

d t l

AWTException

IOException

Exception

ArithmeticException

NullPointerException

program and external circumstances. These errors can be caught and handled by your

Throwable

RuntimeException

Object

NullPointerException

IndexOutOfBoundsException

Several more classes Ill lA tE ti

a d a d ed by youprogram.

LinkageError Several more classes

IllegalArgumentException

Error

AWTError

VirtualMachineError

37

Several more classes

Page 38: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Runtime Exceptions

ClassNotFoundException

IOException

AWTException

p

Exception

R ti E ti

ArithmeticException

NullPointerException

Throwable

RuntimeException

Object

IndexOutOfBoundsException

Several more classes IllegalArgumentException

LinkageError

VirtualMachineError

Several more classes

RuntimeException is caused by i hError

AWTError

Several more classes

programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

38

Several more classes

Page 39: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Checked Exceptions vs. Unchecked ExceptionsUnchecked Exceptions

•RuntimeException, Error and their subclasses are known as uncheckedexceptions.

•All other exceptions are known as checked•All other exceptions are known as checked exceptions:

compiler forces the programmer to check and deal with the exceptions.

39

Page 40: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Unchecked Exceptions

•unchecked exceptions reflect programming logic errors that are not recoverableare not recoverable.

•NullPointerException is thrown if you access an object through a reference variable before an object is assigned g j gto it;

•IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array.

•Unchecked exceptions can occur anywhere in the program.

•Java does not mandate you to write code to catch unchecked exceptions.

40

Page 41: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Checked or Unchecked Exceptions

ClassNotFoundException

IOException

AWTException

IOException

Exception

ArithmeticException

NullPointerException

Throwable

RuntimeException

Object

IndexOutOfBoundsException

Several more classes IllegalArgumentException

LinkageError

VirtualMachineError

Several more classes

Error

AWTError

S l l

Unchecked exception.

41

Several more classes

Page 42: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Declaring, Throwing, and Catching ExceptionsCatching Exceptions

d l timethod1() { try { invoke method2; } catch (Exception ex) {

i

method2() throws Exception { if (an error occurs) { throw new Exception();

}catch exception throw exception

declare exception

Process exception; } }

}}

42

Page 43: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Declaring Exceptionsg p

Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions.

public void myMethod()throws IOException

bli id M th d()public void myMethod()throws IOException, OtherException

43

Page 44: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Throwing Exceptionsg p

When the program detects an error, the program t i t f i tcan create an instance of an appropriate

exception type and throw it. This is known as throwing an exception Here is an examplethrowing an exception. Here is an example,

th Th E ti ()throw new TheException();

TheException ex = new TheException();TheException ex = new TheException();throw ex;

44

Page 45: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Throwing Exceptions Exampleg p p

/** Set a new radius */public void setRadius(double newRadius)

throws IllegalArgumentExceptionthrows IllegalArgumentException {if (newRadius >= 0)

radius = newRadius;else

throw new IllegalArgumentException("R di t b ti ")"Radius cannot be negative");

}

45

Page 46: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Catching Exceptionsg ptry {statements; // Statements that may throw exceptions

}}catch (Exception1 exVar1) {handler for exception1;

}catch (Exception2 exVar2) {catch (Exception2 exVar2) {handler for exception2;

}...catch (ExceptionN exVar3) {handler for exceptionN;

}

46

Page 47: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Catching Exceptionsg p

main method { ... try {

method1 { ...

try {

method2 { ... try {

An exception is thrown in method3 try {

... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; }

try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; }

try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; }

method3

} statement2; }

} statement4; }

} statement6; }

Call StackCall Stack

method1 method1 method1

method2 method2

method3

main method main method main method main method

47

Page 48: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Catch or Declare Checked ExceptionsJava forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException) you must invoke it in a try catch block or declare toRuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException) you have to write the code as shown in (a) or (b)IOException), you have to write the code as shown in (a) or (b).

void p1() { void p1() throws IOException {p () { try { p2(); } catch (IOException ex) {

void p1() throws IOException { p2(); }

... } }

(a) (b)

48

(a) (b)

Page 49: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Example: Declaring, Throwing, and p g gCatching Exceptions

Obj i Thi l d• Objective: This example demonstrates declaring, throwing, and catching exceptions b dif i th tR di th d i thby modifying the setRadius method in the Circle class defined in Chapter 6. The new setRadius method throws an exception ifsetRadius method throws an exception if radius is negative.

TestCircleWithException CircleWithException

49

Page 50: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

The finally Clausey

try {t t tstatements;

}catch(TheException ex) {catch(TheException ex) {handling ex;

}{finally {

finalStatements;}}

50

Page 51: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

{

Suppose no exceptions in the statements

try { statements;

}}catch(TheException ex) { handling ex;

}}finally { finalStatements;

}}

Next statement;

51

Page 52: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

{

The final block is always executed

try { statements;

}}catch(TheException ex) { handling ex;

}}finally { finalStatements;

}}

Next statement;

52

Page 53: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

{

Next statement in the method is executed

try { statements;

}}catch(TheException ex) { handling ex;

}}finally { finalStatements;

}}

Next statement;

53

Page 54: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;

Suppose an exception of type Exception1 is thrown in statement2statement1;

statement2;statement3;

}

statement2

}catch(Exception1 ex) { handling ex;

}{finally {

finalStatements; }

Next statement;

54

Page 55: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;

The exception is handled.statement1;statement2;statement3;

}}catch(Exception1 ex) { handling ex;

}{finally {

finalStatements; }

Next statement;

55

Page 56: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;

The final block is always executed.statement1;

statement2;statement3;

}}catch(Exception1 ex) { handling ex;

}{finally {

finalStatements; }

Next statement;

56

Page 57: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;

The next statement in the method is now executed.statement1;

statement2;statement3;

}}catch(Exception1 ex) { handling ex;

}{finally {

finalStatements; }

Next statement;

57

Page 58: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;statement2;

statement2 throws an exception of type E ception2statement3;

}catch(Exception1 ex) { handling ex;

Exception2.

handling ex; }catch(Exception2 ex) { handling ex; throw ex;

}finally { finalStatements;finalStatements;

}

Next statement;

58

Page 59: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;statement2;

Handling exception

statement3;}catch(Exception1 ex) { handling ex;handling ex;

}catch(Exception2 ex) { handling ex; throw ex;

}finally { finalStatements;finalStatements;

}

Next statement;

59

Page 60: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;statement2;

Execute the final block

statement3;}catch(Exception1 ex) { handling ex;handling ex;

}catch(Exception2 ex) { handling ex; throw ex;

}finally { finalStatements;finalStatements;

}

Next statement;

60

Page 61: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Trace a Program Executionanimation

try { statement1;statement2;

Rethrow the exception and control is transferred to the callerstatement3;

}catch(Exception1 ex) { handling ex;

caller

handling ex; }catch(Exception2 ex) { handling ex; throw ex;

}finally { finalStatements;finalStatements;

}

Next statement;

61

Page 62: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

Cautions When Using Exceptionsg p

• Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify.

• Be aware, however, that exception handling usually requires more time and resourcesusually requires more time and resources because it requires instantiating a new exception object rolling back the call stack andexception object, rolling back the call stack, and propagating the errors to the calling methods.

62

Page 63: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

When to Throw Exceptionsp

• An exception occurs in a method.

• If you want the exception to be processed by its caller you should create an exception objectcaller, you should create an exception object and throw it.

• If you can handle the exception in the method where it occurs, there is no need to throw it.

63

Page 64: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

When to Use Exceptionsp

When should you use the try-catch block in the code? You should use it to deal with unexpected errorYou should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code is inefficient

try {

System.out.println(refVar.toString());y p g

}

catch (NullPointerException ex) {

System.out.println("refVar is null");

}

64

Page 65: Lecture 23: Interfaces; Event Programmingeugene/cs170/lectures/lecture23-interfaces.pdf• An interface is a class-like construct that contains only constants and abstract methodscontains

When to Use Exceptionsp

is better to be replaced by

if (refVar != null)

System out println(refVar toString());System.out.println(refVar.toString());

else

System.out.println("refVar is null");y p

65