87
Exception Jiafan Zhou

Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Embed Size (px)

Citation preview

Page 1: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Exception

Jiafan Zhou

Page 2: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Java Exception Handling Exception = an event that occurs during the execution of a

program that disrupts the normal flow of instructions: Examples: Hard disk crash; Out of bounds array access; Divide by

zero, etc When an exception occurs, the executing method creates

an Exception object and hands it to the runtime system--``throwing an exception''

The runtime system searches the runtime call stack for a method with an appropriate handler, which ``catches the exception''

Page 3: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Exception Policy Java is fussy about (some) exceptions, requiring that the

programmer either: deal with the exceptions when they occur, using try and catch, or

explicitly hand off the exception to the method that calls the method in which the exception occurs, effectively ``passing the buck'' to the calling method.

The exceptions Java is fussy about are called ''checked'' exceptions, because the compiler will check that one of the above options is satisfied

Page 4: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Advantages of Java Exception Handling

1. Separating Error Handling Code from Regular Code

2. Propagating Errors Up the Call Stack

3. Grouping Error Types and Error Differentiation

Page 5: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Advantage 1:Separating Error Handling Code from ``Regular'' Code

readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file;}

Example: Here is pseudocode for reading a file into memory:

Page 6: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Problems with readFile

What happens if the file can't be opened? What happens if the length of the file can't

be determined? What happens if enough memory can't be

allocated? What happens if the read fails? What happens if the file can't be closed?

Page 7: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Error Handling With Traditional Programming

errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode;}

Page 8: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Error Handling With JavareadFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; }}

Note that the error handling code and ``regular'' code areseparate

Page 9: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Advantage 2:Propagating Errors Up the Call Stack

method1 { call method2;}method2 { call method3;}method3 { call readFile;}

method1

method2

method3

readFile

Call Stack

Suppose also that method1 is the only method interested in the errors that occur within readFile.

How does the error code get propogated up the stack?

call

call

call

Page 10: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Propagating Errors Using Traditional Programming

method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed;}errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed;}errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed;}

method1

method2

method3

readFile

Call Stack

call

call

callreturn

return

return

Page 11: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Propagating Errors Using Java

method1 { try { call method2; } catch (exception) { doErrorProcessing; }}method2 throws exception { call method3;}method3 throws exception { call readFile;}

method1

method2

method3

readFile

Call Stack

call

call

call

throw

Page 12: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Advantage 3:Grouping Error Types and Error Differentiation

Java exceptions are first class Java objects, and so theyare grouped into a class hierarchy. For example:

Exception

RunTimeException

ArithmeticException

NullPointerException

IOException

FileNotFoundException

MalformedURLException

Page 13: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Example

method1 { try { call method2; } catch(Exception) { doErrorProcessing; }}method2 throws ArithmeticException { ... call method3; ...}method3 throws FileNotFoundException { ... call method4; ...}method4 throws NullPointerException { ...}

Suppose (remember, this is pseudocode):

Page 14: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Throwing Structure

method1

method2

method3

method4

Call Stack

call

call

call

throw

In this case, the exception handler in method1 musthandle all exception types

Page 15: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Modified Example

method1 { try { call method2; } catch(RunTimeException) { doErrorProcessing; }}method2 throws ArithmeticException { ... call method3; ...}method3 throws FileNotFoundException { ... call method4; ...}method4 throws NullPointerException { ...}

Page 16: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

New Throwing Structure

method1

method2

method3

method4

Call Stack

call

call

callthrow

In this case, method1 will handle only runtimeexceptions.

Any FileNotFoundException thrown by method3 will have to be handled further down the stack.

Page 17: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Another Modified Examplemethod1 { try { call method2; } catch(RunTimeException) { doErrorProcessing; }}method2 throws ArithmeticException { try { ... call method3; ... } catch(IOException) { doMoreErrorProcessing; }}method3 throws FileNotFoundException { ... call method4; ...}method4 throws NullPointerException { ...}

Page 18: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

New Throwing Structure

method1

method2

method3

method4

Call Stack

call

call

call

throw

Page 19: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

FileCopy Example Revisitedimport java.io.*;

public class FileCopy1 {

public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r; FileWriter w;

System.out.print("Source file name: "); String inFileName = br.readLine(); r = new FileReader(inFileName);

System.out.print("Destination file name: "); String outFileName = br.readLine(); w = new FileWriter(outFileName);

int c;

while ((c = r.read()) != -1) w.write(c); w.flush(); }}

Page 20: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

If The Input File Does Not Exist

4% java FileCopy1Source file name: fooException in thread "main" java.io.FileNotFoundException: foo (No such file or directory)

at java.io.FileInputStream.open(Native Method)at java.io.FileInputStream.<init>(FileInputStream.java:103)at java.io.FileInputStream.<init>(FileInputStream.java:66)at java.io.FileReader.<init>(FileReader.java:39)at FileCopy.main(FileCopy.java:12)

5%

In the example, the main method chooses to ''passthe buck'', but there is nowhere to pass it to.

Thus, the program will crash:

Page 21: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Catching the Exceptionpublic class FileCopy2 {

public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r; FileWriter w;

System.out.print("Source file name: "); String inFileName = br.readLine(); try { r = new FileReader(inFileName); } catch(FileNotFoundException ex) { System.out.println(ex.getMessage()); System.out.print("Source file name: "); inFileName = br.readLine(); r = new FileReader(inFileName); }

... }}

Page 22: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Catching the ExceptionThis approach will catch the first instance of a FileNotFoundException, but only that instance:

5% java FileCopy2Source file name: foofoo (No such file or directory)Source file name: barException in thread "main" java.io.FileNotFoundException: bar (No such file or directory)

at java.io.FileInputStream.open(Native Method)at java.io.FileInputStream.<init>(FileInputStream.java:103)at java.io.FileInputStream.<init>(FileInputStream.java:66)at java.io.FileReader.<init>(FileReader.java:39)at FileCopy.main(FileCopy.java:19)

6%

Note that you can use the getMessage() method(inherited by the Exception class) in your handler.

Page 23: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Generating True Looping Behaviorpublic class FileCopy3 {

public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); FileReader r = null; FileWriter w = null;

boolean fileFound; do { fileFound = true; System.out.print("Source file name: "); String inFileName = br.readLine(); try { r = new FileReader(inFileName); } catch(FileNotFoundException ex) { fileFound = false; System.out.println(ex.getMessage()); } } while ( !fileFound ); ... }}

Page 24: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

New Output226% java FileCopy3Source file name: foofoo (No such file or directory)Source file name: barbar (No such file or directory)Source file name: foofoo (No such file or directory)Source file name: barbar (No such file or directory)Source file name: X.javaDestination file name: Y.java227%

Page 25: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Another Way public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

FileReader r = getFileReader(br); FileWriter w = getFileWriter(br);

int c;

while ((c = r.read()) != -1) w.write(c); w.flush();

}

Page 26: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

A Version of main that Does Not throw

public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

FileReader r = getFileReader(br); FileWriter w = getFileWriter(br);

int c;

try { while ((c = r.read()) != -1) w.write(c); w.flush(); } catch(IOException ex) { System.out.println(ex.getMessage()); } }

Now the program will not crash if/when an I/O erroroccurs.

Page 27: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Checked vs. Unchecked Exceptions A program that catches all I/O exceptions may

still experience a different type of exception (say, a runtime exception)

I/O exceptions are ``checked'' by the compiler That is, you are required to either catch them or

mention them in a throws clause Unlike I/O exceptions, runtime exceptions are

``unchecked'' That is, you can choose to ignore them at your peril

Page 28: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Some Checked Exceptions

IOException and any of its subclasses InterruptedException (thrown when a

thread is interrupted) Any exception you invent by subclassing Exception

Page 29: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Some Unchecked Exceptions Subclasses of RuntimeException:

ArithmeticExceptionIllegalArgumentExceptionNumberFormatExceptionIndexOutOfBoundsException

ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException

NullPointerExceptionThose that you invent by subclassing RuntimeException

Page 30: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Exceptions vs. Errors

Exceptions are processing conditions that a program ought to be able to recover from if it is robust enough

Errors are conditions that are ordinarily not recoverable:Death of a threadLinking errorVirtual machine error

Page 31: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

The Throwable Class Exceptions and Errors are both

subclasses of the Throwable class:

Object

Throwable

ErrorException

LinkageError ThreadDeath VirtualMachineError

Page 32: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Finally Statements inside finally block are guaranteed to

be executed. With or without thrown exceptions.

try{//allocate system resource}catch (Exception1 e){}catch(Exception2 e){}finally{//free up system resource }

Page 33: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Multi Catch In Java 7 or later, it is possible to handle more than one type

of exception in a single catch block

try{//allocate system resource}catch (Exception1 ¦ Exception2 ex){// exception handling}

MultiCatchDemo.java

In multi catch, the catch parameter (above ex) is implicitly final. So it is not possible to assign any values to it within the catch block.

Page 34: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Try With Resources In Java 7 or later, it is possible to use a try-with-resources

statement which is a try declares on resources that isauto closable.

The resource defined in the try-with-resource must implement the java.lang.AutoCloseable interface

Prior to Java7, we use the finally block

TryWithResourceDemo.java

Page 35: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Polymorphism

Jiafan Zhou

Page 36: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

PolymorphismPolymorphism

Poly- means many, morph means changes.Polymorphism means many changes (method behaviours) for the objects.

It provides another dimension of separation of interface from implementation. (decouple what from how)

Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance.

Page 37: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Encapsulation vs. Encapsulation vs. PolymorphismPolymorphism

Encapsulation

Encapsulation creates new data types by combining characteristics and behaviors.

Implementation hiding separates the interface from the implementation by making the details private

Polymorphism

It deals with decoupling in terms of types.

Inheritance allows the treatment of an object as its own type or its base type

Many types (derived from the same base type) can be treated as one type, and a single piece of code to work on all those different types equally.

Page 38: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Late BindingLate Binding

Late binding is also called

Dynamic binding

or Runtime binding

Page 39: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Note ClassNote Class

public class Note {

private String noteName;

private Note(String noteName) {

this.noteName = noteName;

}

public String toString() {

return noteName;

}

public static final Note MIDDLE_C = new Note("Middle C");

public static final Note C_SHARP = new Note("C Sharp");

public static final Note B_FLAT = new Note("B Flat");

// Etc.

}

This is an “enumeration” class, which has a fixed number of constant objects to choose from.Note.MIDDLE_C, Note.C_SHARP and Note.B_FLAT

You can’t make additional objects because the constructor is private.

Notice: Java also supports enum class, but here we simulate the use of Java enum.

Page 40: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Instrument & Instrument & Wind ClassWind Class

public class Instrument {

public void play(Note n) {

}

}

public class Wind extends Instrument {

// Override the method play(Note):

public void play(Note n) {

System.out.println("Wind.play(): " + n);

}

}

Page 41: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Music classMusic class

public class Music {

public static void tune(Instrument i) {

i.play(Note.MIDDLE_C);

}

public static void main(String[] args) {

Wind flute = new Wind();

tune(flute);

}

}

the method Music.tune( ) accepts an Instrument reference, but also anything derived from Instrument.

Page 42: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Forgetting the Forgetting the object typeobject type

In Music.java, why intentionally forget the type of an object?

Can we ask tune( ) to simply takes a Wind reference?

If you did that, you’d need to write a new tune( ) for every type of Instrument in your system.

Suppose you add two more classes Stringed and Brass

Page 43: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Stringed and Stringed and Brass classBrass class

class Stringed extends Instrument { public void play(Note n) { System.out.println("Stringed.play(): " + n); }}

class Brass extends Instrument { public void play(Note n) { System.out.println("Brass.play(): " + n); }}

Page 44: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Music2 classMusic2 classpublic class Music2 { public static void tune(Wind i) { i.play(Note.MIDDLE_C); } public static void tune(Stringed i) { i.play(Note.MIDDLE_C); } public static void tune(Brass i) { i.play(Note.MIDDLE_C); } public static void main(String[] args) { Wind flute = new Wind(); Stringed violin = new Stringed(); Brass frenchHorn = new Brass(); tune(flute); // No upcasting tune(violin); tune(frenchHorn)}}

"Wind.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C"

This works, but…

Drawback: you must write type-specific methods for each new Instrument class you add.

It’s better to just write a single method that takes the base class as its argument, and not any of the specific derived classes!

That’s exactly what polymorphism allows you to do.

Page 45: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Question Question

public static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C); }

How can the compiler possibly know that this Instrument reference points to a Wind in this case and not a Brass or Stringed?

The compiler can’t. To get a deeper understanding of the issue, it’s helpful to examine the subject of binding.

Page 46: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Method-call Method-call bindingbinding

Connecting a method call to a method body is called binding.

early binding: binding is performed before the program is run by the complier.

late binding: binding occurs at run time, based on the type of object.

Early binding is also called compile binding or static binding. Late binding is also called runtime binding or dynamic binding

All method binding in Java uses late binding unless the method is static or final (private methods are implicitly final)

Page 47: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Producing the right Producing the right behaviorbehavior

The classic example in OOP is the “shape” example.

The shape example has a base class called Shape and various derived types: Circle, Square, Triangle, etc.

The inheritance diagram shows the relationships:

Page 48: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

The inheritance The inheritance diagram diagram

Page 49: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Late bindingLate binding

Shape s = new Circle(); //simply upcasting

You can say, “a cricle is a shape”

Suppose you call one of the base-class methods (that have been overridden in the derived classes): s.draw();

You might expect that Shape’s draw( ) is called

And yet the Circle.draw( ) is called because of late binding (polymorphism).

Page 50: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

ExtensibilityExtensibility

Because of polymorphism, you can add as many new types as you want to the system without changing the tune( ) method.

In a well-designed OOP program, most or all of your methods will communicate only with the base-class interface. Such a program is extensible.

You can add new functionality by inheriting new data types from the base class. The methods that manipulate the base-class interface will not need to be changed at all to accommodate the new classes

Page 51: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Add new Add new instrumentsinstruments

Page 52: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

class Instrument { void play(Note n) { System.out.println("Instrument.play() " + n); } String what() { return "Instrument"; } void adjust() {}}

class Wind extends Instrument { void play(Note n) { System.out.println("Wind.play() " + n); } String what() { return "Wind”; } void adjust() {}}

class Percussion extends Instrument { void play(Note n) { System.out.println("Percussion.play() " + n); } String what() { return "Percussion"; } void adjust() {}}

class Stringed extends Instrument { void play(Note n) { System.out.println("Stringed.play() " + n); } String what() { return "Stringed"; } void adjust() {}}

class Brass extends Wind { void play(Note n) { System.out.println("Brass.play() " + n); } void adjust() { System.out.println("Brass.adjust()"); }}

class Woodwind extends Wind { void play(Note n) { System.out.println("Woodwind.play() " + n); } String what() { return "Woodwind"; }}

Page 53: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Music3 exampleMusic3 example

public class Music3 { // Doesn't care about type, so new types // added to the system still work right: public static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C); } public static void tuneAll(Instrument[] e){ for(int i = 0; i < e.length; i++) tune(e[i]); }

public static void main(String[] args) { // Upcasting during addition to the array: Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() }; tuneAll(orchestra); }}

"Wind.play() Middle C", "Percussion.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C", "Woodwind.play() Middle C"

tune( ) does not know the code changes that have happened around it.

polymorphism is an important technique for the programmer to “separate the things that change from the things that stay the same”.

Page 54: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Pitfall: “overriding” Pitfall: “overriding” private methodsprivate methods

public class PrivateOverride { private void f() { System.out.println("private f()"); } public static void main(String[] args) { PrivateOverride po = new Derived(); po.f(); }}

class Derived extends PrivateOverride { public void f() { System.out.println("public f()"); }}

"private f()"

Remember: a private method is automatically final, and is also hidden from the derived class.

So Derived’s f( ) in this case is a brand new method.It’s not even overloaded, since the base-class version of f( ) isn’t visible in Derived.

Page 55: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Abstract classes and Abstract classes and methodsmethods

In all previous instrument examples, the methods in the base class Instrument were always “dummy” methods.

If these methods are ever called, you’ve done something wrong.

That’s because the intent of Instrument is to create a common interface for all the classes derived from it

Page 56: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Abstract class & Abstract class & methodmethod

The only reason to establish this common interface is so it can be expressed differently for each different subtype.

Another way of saying this is to call Instrument an abstract base class (or simply an abstract class).

Instrument expresses only the interface, not implementation, you’ll probably want to prevent the user from creating object from it.

Page 57: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Abstract MethodAbstract Method

One solution: let methods in base class print error message whenever being invoked.

This delays the information until the run time. It’s better to catch the problem at the compile time.

Java provides a mechanism for doing this called the abstract method.

This is a method that is incomplete; it has only a declaration and no method body.

abstrct void f();

Page 58: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Abstract ClassAbstract Class

A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class itself must be qualified as abstract.

You cannot create an object of an abstract class, since an abstract class is incomplete.

This way, the compiler ensures the purity of the abstract class, and you don’t need to worry about misusing it.

It’s possible to create a class as abstract without including any abstract methods. This is useful when you want to prevent any instance from this class.

Page 59: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Inherit from Inherit from Abstract ClassAbstract Class

If you inherit from an abstract class and you want to make objects of the new type, you must provide method definitions for all the abstract methods in the base class.

Otherwise, then the derived class is also abstract, and the compiler will force you to qualify that class with the abstract keyword.

Page 60: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Abstract InstrumentAbstract Instrument

Page 61: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

abstract class Instrument { private int i; // Storage allocated for each public abstract void play(Note n); public String what() { return "Instrument"; } public abstract void adjust();}

class Wind extends Instrument { public void play(Note n) { System.out.println("Wind.play() " + n); } public String what() { return "Wind"; } public void adjust() {}}

class Percussion extends Instrument { public void play(Note n) { System.out.println("Percussion.play() " + n); } public String what() { return "Percussion"; } public void adjust() {}}

class Stringed extends Instrument { public void play(Note n) { System.out.println("Stringed.play() " + n); } public String what() { return "Stringed"; } public void adjust() {}}

class Brass extends Wind { public void play(Note n) { System.out.println("Brass.play() " + n); } public void adjust() { System.out.println("Brass.adjust()"); }}

class Woodwind extends Wind { public void play(Note n) { System.out.println("Woodwind.play() " + n); } public String what() { return "Woodwind"; }}

Page 62: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

public class Music4 { // Doesn't care about type, so new types // added to the system still work right: static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C); }

static void tuneAll(Instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); }

public static void main(String[] args) { // Upcasting during addition to the array: Instrument[] orchestra = { new Wind(), new Percussion(), new Stringed(), new Brass(), new Woodwind() }; tuneAll(orchestra); }}

"Wind.play() Middle C", "Percussion.play() Middle C", "Stringed.play() Middle C", "Brass.play() Middle C", "Woodwind.play() Middle C"

There’s really no change except in the base class.

It’s helpful to create abstract classes and methods because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used

Page 63: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Designing with Designing with inheritanceinheritance

You might think “everything ought to be inherited, because polymorphism is such a clever tool.”

This can burden your designs!! You code will become needlessly complicated.

A better approach is to choose composition first, especially when it’s not obvious which one you should use.

Page 64: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

abstract class Actor { public abstract void act();}

class HappyActor extends Actor { public void act() { System.out.println("HappyActor"); }}

class SadActor extends Actor { public void act() { System.out.println("SadActor"); }}

class Stage { private Actor actor = new HappyActor(); public void change() { actor = new SadActor(); } public void performPlay() { actor.act(); }}

public class Transmogrify { public static void main(String[] args) { Stage stage = new Stage(); stage.performPlay(); stage.change(); stage.performPlay(); }}

"HappyActor", "SadActor"

A Stage object contains a reference to an Actor, which can be dynamically bound to different object.

The behavior produced by performPlay( ) changes which gives dynamicflexibility at run time.

This is called State Pattern in Design Pattern.

Page 65: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Pure inheritance vs. Pure inheritance vs. extensionextension

Pure inheritance: only methods established in the base class or interface are to be overridden in the derived class.

derived class will have the interface of the base class and nothing less.

derived classes will also have no more than the base-class interface.

Page 66: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

““Is-a”Is-a”

The base class can receive any message you can send to the derived class because the two have exactly the same interface.

All you need to do is upcast from the derived class and never look back to see what exact type of object you’re dealing with.

Page 67: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

““Is-Like-a”Is-Like-a”

the derived class is like the base class—it has the same fundamental interface

but it has other features that require additional methods to implement

Page 68: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Drawback of Drawback of Is-Like-aIs-Like-a

The extended part of the interface in the derived class is not available from the base class.

so once you upcast, you can’t call the new methods:

Page 69: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

DowncastDowncast

You lose the specific type information via an upcast.

To retrieve the type information: move back down the inheritance hierarchy—you use a downcast.

upcast is always safe; the base class cannot have a bigger interface than the derived class.

But with a downcast, you don’t really know that a shape (for example) is actually a circle.

Page 70: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

There must be some way to guarantee that a downcast is correct.

You get a ClassCastException.

At run time this cast is checked to ensure that it is in fact the type you think it is. In java this scheme is called run-time type identification (RTTI)What will happen if it isn’t?

Page 71: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

class Useful { public void f() {} public void g() {}}

class MoreUseful extends Useful { public void f() {} public void g() {} public void u() {} public void v() {} public void w() {}}

public class RTTI { public static void main(String[] args) { Useful[] x = { new Useful(), new MoreUseful() }; x[0].f(); x[1].g();

// Compile time: method not found in Useful: //! x[0].u();

((MoreUseful)x[1]).u(); // Downcast/RTTI ((MoreUseful)x[0]).u(); // Exception thrown }}

Page 72: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Homework

Page 73: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Homework Update your existing banking system with proper inheritance hierarchy. Design the object model of the banking system

e.g. Current account, deposit account etc. Design the exception in your banking system. Update the client(menu) that uses the banking system

Page 74: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

Questions & Answers

Page 75: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

75

Mock Exam Questions:Question 44. Given:31. // some code here32. try {33. // some code here34. } catch (SomeException se) {35. // some code here36. } finally {37. // some code here38. }

Under which three circumstances will the code on line 37 be executed?(Choose three.)A. The instance gets garbage collected.B. The code on line 33 throws an exception.C. The code on line 35 throws an exception.D. The code on line 31 throws an exception.E. The code on line 33 executes successfully.

Page 76: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

76

Mock Exam Questions:Question 19Given:1. class TestA {2. public void start() { System.out.println(”TestA”); }3. }4. public class TestB extends TestA {5. public void start() { System.out.println(”TestB”); }6. public static void main(String[] args) {7. ((TestA)new TestB()).start();8. }9. }

What is the result?A. TestAB. TestBC. Compilation fails.D. An exception is thrown at runtime.

Page 77: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

77

Mock Exam Questions:Question 21Given:11. public abstract class Shape {12. int x;13. int y;14. public abstract void draw();15. public void setAnchor(int x, int y) {16. this.x = x;17. this.y = y;18. }19. }and a class Circle that extends and fully implements the Shape class.Which is correct?A. Shape s = new Shape();s.setAnchor(10,10);s.draw();B. Circle c = new Shape();c.setAnchor(10,10);c.draw();C. Shape s = new Circle();s.setAnchor(10,10);s.draw();D. Shape s = new Circle();s->setAnchor(10,10);s->draw();E. Circle c = new Circle();c.Shape.setAnchor(10,10);c.Shape.draw();

Page 78: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

78

Mock Exam Questions:Question 27Given:11. public static void parse(String str) {12. try {13. float f= Float.parseFloat(str);14. } catch (NumberFormatException nfe) {15. f= 0;16. } finally {17. System.out.println(f);18. }19. }20. public static void main(String[] args) {21. parse(”invalid”);22. }What is the result?A. 0.0B. Compilation fails.C. A ParseException is thrown by the parse method at runtime.D. A NumberFormatException is thrown by the parse method atruntime.

Page 79: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

79

Mock Exam Questions:Question 57Given:11. Float pi = new Float(3.14f);12.if(pi>3) {13. System.out.print(”pi is bigger than 3. “);14. }15. else {16. System.out.print(”pi is not bigger than 3. “);17. }18. finally {19. System.out.println(”Have a nice day.”);20. }

‘What is the result?A. Compilation fails.B. pi is bigger than 3.C. An exception occurs at runtime.D. pi is bigger than 3. Have a nice day.E. pi is not bigger than 3. Have a nice day.

Page 80: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

80

Mock Exam Questions:

Question 68Click the Exhibit button.SomeException:1. public class SomeException {2. }Class A:1. public class A {2. public void doSomething() { }3. }Class B:1. public class B extends A {2. public void doSomething() throws SomeException { }3. }

Which is true about the two classes?A. Compilation of both classes will fail.B. Compilation of both classes will succeed.C. Compilation of class A will fail. Compilation of class B will succeed.D. Compilation of class B will fail. Compilation of class A will succeed.

Page 81: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

81

Mock Exam Questions:Question 69Click the Exhibit button.Class TestException1. public class TestException extends Exception {2. }Class A:1. public class A {2.3. public String sayHello(String name) throws TestException {4.5. if(name == null) {6. throw new TestException();7. }8.9. return “Hello “+ name;10. }11.12. }

A programmer wants to use this code in an application:45. A a=new A();46. System.out.println(a.sayHello(”John”));Which two are true? (Choose two.)A. Class A will not compile.B. Line 46 can throw the unchecked exception TestException.C. Line 45 can throw the unchecked exception TestException.D. Line 46 will compile if the enclosing method throws a TestException.E. Line 46 will compile if enclosed in a try block, where TestExceptionis caught.

Page 82: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

82

Mock Exam Questions:Question 70Given:33. try {34. // some code here35. } catch (NullPointerException e1) {36. System.out.print(”a”);37. } catch (RuntimeException e2) {38. System.out.print(”b”);39. } finally {40. System.out.print(”c”);41. }What is the result if a NullPointerException occurs on line 34?A. cB. aC. abD. acE. bcF. abc

Page 83: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

83

Mock Exam Questions:Question 71Given:11.classA {12. public void process() { System.out.print(”A,”); } }13. class B extends A {14. public void process() throws IOException {15. super.process();16. System.out.print(”B,”);17. throw new IOException();18. } }19. public static void main(String[] args) {20. try { new B().process(); }21. catch (IOException e) { System.out.println(”Exception”); } }

What is the result?A. ExceptionB. A,B,ExceptionC. Compilation fails because of an error in line 20.D. Compilation fails because of an error in line 14.E. A NullPointerException is thrown at runtime.

Page 84: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

84

Mock Exam Questions:

Question 72Given:11.classA {12. public void process() { System.out.print(”A “); } }13. class B extends A {14. public void process() throws RuntimeException {15. super.process();16. if (true) throw new RuntimeException();17. System.out.print(“B”); }}18. public static void main(String[] args) {19. try { ((A)new B()).process(); }20. catch (Exception e) { System.out.print(”Exception “); }21. }

What is the result?A. ExceptionB. A ExceptionC. A Exception BD. A B ExceptionE. Compilation fails because of an error in line 14.F. Compilation fails because of an error in line 19.

Page 85: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

85

Mock Exam Questions:Question 73Given:11. public classA {12. void process() throws Exception { throw new Exception(); }13. }14. public class B extends A {15. void process() { System.out.println(”B “); }16. }17. public static void main(String[] args) {18.A a=new B();19. a.process();20.}What is the result?A. BB. The code runs with no output.C. An exception is thrown at runtime.D. Compilation fails because of an error in line 15.E. Compilation fails because of an error in line 18.F. Compilation fails because of an error in line 19.

Page 86: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

86

Mock Exam Questions:Question 74Given:11. public class A {12. void process() throws Exception { throw new Exception(); }13. }14. public class B extends A {15. void process() { System.out.println(”B”); }16. }17. public static void main(String[] args) {18. new B().process();19. }

What is the result?A. BB. The code runs with no output.C. Compilation fails because of an error in line 12.D. Compilation fails because of an error in line 15.E. Compilation fails because of an error in line 18.

Page 87: Exception Jiafan Zhou. Java Exception Handling Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:

87

Mock Exam Questions:Question 75Given:84. try {85. ResourceConnection con = resourceFactory.getConnection();86. Results r = con.query(”GET INFO FROM CUSTOMER”);87. info = r.getData();88. con.close();89. } catch (ResourceException re) {90. errorLog.write(re.getMessage());91. }92. return info;

Which is true if a ResourceException is thrown on line 86?A. Line 92 will not execute.B. The connection will not be retrieved in line 85.C. The resource connection will not be closed on line 88.D. The enclosing method will throw an exception to its caller.