events and exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 ·...

30
Events and Exceptions Analysis and Design of Embedded Systems and OO* Object-oriented programming Jan Bendtsen Automation and Control

Upload: others

Post on 09-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Events and Exceptions

Analysis and Design of Embedded Systems and OO*

Object-oriented programmingJan Bendtsen

Automation and Control

Page 2: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Lecture Outline

Exceptions

Throwing and catching Exceptions

creating and throwing exceptions the try-catch() construct

Events

Simple file I/O

Streams, readers and writers The File Class java.io.Serializable

Page 3: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

...

Page 4: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Error-prone activities

Consider a (C or similar) function that does the following:

void readFile() {

// Open a file;

// Determine its size;

// Allocate that much memory;

// Read the file into memory;

// Close the file;

}

Page 5: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Error-prone activities

Consider a (C or similar) function that does the following:

void readFile() {

// Open a file; - Oops! The file does not exist

// Determine its size; - Oops! The file size cannot be determined

// Allocate that much memory; - Oops! Out of memory!

// Read the file into memory; - Oops! File corrupted!

// Close the file; - Oops! Lost connection

}

Page 6: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Traditional error handling. . .

if (readFailed()) {

errorCode = -1;

}

} else {

errorCode = -2;

}

} else {

errorCode = -3;

. . .

}

return errorCode;

}

errorCodeType readFile {

errorCodeType errorCode = 0;

// Variable declarations

FILE fp == fopen(”MyFile.txt”,”r”);

if (fp != NULL) {

fileLength = getFileLength();

if (fileLength > 0) {

buffer = malloc(fileLength*sizeof(int));

if (buffer != NULL) {

// allocation went OK, read// the file into memory;

. . .

Page 7: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Traditional error handling

The actual code tends to drown in ”if (...) { ... } else { // error handling } ” constructs

The logical flow of the code is interrupted

=> it is easy to lose the overview (the error handling code may itself introduce errors)

=> it is easy to forget to handle errors (buggy software)

Page 8: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Exceptionscatch(FileOpenFailed) {

// Error handling for file opening

} catch(sizeDeterminationFailed) {

// Error handling for file size

} catch(memoryAllocationFailed) {

// Error handling for malloc

} catch(FileReadFailed) {

// Error handling for read failure

} catch(FileCloseFailed) {

// Error handling for lost conn.

// etc.

}

}

void readFile() {

try {

// Open a file;

// Determine its size;

// Allocate that much memory;

// Read the file into memory;

// Close the file;

}

. . .

Page 9: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Exceptions

Exceptions are objects generated when the normal program flow is interrupted

They are only generated when needed

They can be used to delegate information of a failure or other event to a place in your program that is geared to handle it, thus improving the robustness of your software

They don't save you any work

... but they can improve the readability and logical flow of your code quite a lot

Page 10: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Exceptions as classes

java.lang.Throwable

IOException

#msg: String+IOException()+IOException(String s)+getMessage()

project.io

FileOpenException

+getFileName()+getFile()

#filename: String

java.lang.Exception

Page 11: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Using exceptions

Exceptions are standard objects that must be a (possibly distant) subclass of java.lang.Exception

When somethings goes wrong, an exception object is created (using a constructor, just like any other object) and then either handled immediately or thrown

Once thrown, the program execution is halted

The exception is then passed down the call stack until an appropriate code segment is able to process them. This is called catching an exception

If an exception is not caught at some point, the program dies

Page 12: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Throwing exceptions

main

Method without error handler

Method where error occurs

Method with error handler

Generates and throws an exception

Looking forappropriatehandler

Looking forappropriatehandler

Catches exception

Forwards exception

Method calls

Page 13: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Throwing Exceptions in Java Where the exception occurs:

public double computeOutput(double input) throws SingularMatrixException {

if (D.isSingular()) { throw new SingularMatrixException(

“D is not invertible!”);}// Computations

...

In the invoking method:public Vector computeOutput(Vector inputs) throws SingularMatrixException {

...

for(Double input : inputs) { v.add(computeOutput(input.doubleValue()));

}

...

Page 14: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Catching Exceptions in Java Error handling code

public void compute() {...try {

Vector v = system.computeOutput(theValues);...

} catch (SingularMatrixException sme) {// Do the necessary to handle singular matrices

...}

Page 15: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Events

Events are similar to Exceptions, in that they are generated when “something happens”

They are typically generated in connection with user interaction, e.g., mouse clicks etc.

Unlike Exceptions, they are not thrown down the call stack, but rather handed over to an Event Listener which acts as an event handler;

If they are not caught, the program typically does not die

No try-catch construct, just ordinary method calls

Page 16: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Z

The Event Listener model

JMenu

JSpinner

JButton

Return

Space

UIWindow

SettingsManager

PlayerCharacter

Event listenersEvent sources

Page 17: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Events in Java

First thing to do is add one or more event listener objects to the event source object(s) involved:

public class Simulator extends JFrame implements ActionListener {

// Constructor

public Simulator() {JButton startBtn = new JButton(“Start”);JButton stopBtn = new JButton(“Stop”);startBtn.addActionListener(this);stopBtn.addActionListener(this);

...

This way, both startBtn and stopBtn are able to hand over Action events to the Simulator object.

Page 18: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Events in Java

In order to receive events, an appropriate event handling method must be implemented:

public class Simulator extends JFrame implements ActionListener {

...

public void actionPerformed(ActionEvent ae) {

String buttonLabel = ae.getActionCommand();

if (buttonLabel.equals(“Start”)) {

startSimulation();

} else {

stopSimulation();

}

}

Page 19: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

UML

Simulator

-startButton: JButton-endButton: JButton

+actionPerformed(ActionEvent ae)-startSimulation()-stopSimulation()

JFrame ActionListener

Page 20: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

File I/O in Java

I/O is abstracted to a high degree in Java

I/O is centered around the concept of streams

disk files

devices

other programs

memory arrays

...

They can be of different types

byte streams

character streams

object streams

Page 21: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Basic Streams

Reading datainto a program

Writing datafrom a program

Page 22: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Streams in Java Streams are, of course, objects

Programs typically use byte streams to perform input and output of 8-bit bytes

All byte stream classes inherit from InputStream and OutputStream

For instance, if the source/destination are files, one could use

FileInputStream

FileOutputStream

However, if we are working with text (i.e., characters), it is more convenient to use Reader and Writer objects

FileReader

FileWriter

Page 23: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Character-based I/O public static void main(String[ ] args) throws IOException {

FileReader in = null;

FileWriter out = null;

try {

in = new FileReader("xanadu.txt");

out = new FileWriter("outagain.txt");

int c;

// character by character...

while ((c = in.read()) != -1) { out.write(c); }

} finally {

if (in != null) { in.close(); }

if (out != null) { out.close(); }

}

}

Page 24: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Streams, Readers and Writers

Rather than having to work with raw bytes or individual characters, it is often convenient to wrap streams in formatted ”readers” and ”writers”:

try {input = new BufferedReader(new

FileReader("xanadu.txt"));output = new PrintWriter(new

FileWriter("characteroutput.txt"));String line;while ((line = input.readLine()) != null) {

output.println(line);}

} catch(FileNotFoundException e) {System.out.println(”Could not find file!”);

} ...

Page 25: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Streams, Readers and Writers

Physical file

Byte stream

Basic Reader

Formatted Reader

Program

Page 26: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

File objects in Java The File class hides underlying OS-specific details from the user;

consider for instance

File fil = new File(“slides3.pdf”);

On a Linux system, fil.getAbsolutePath() might return

/home/dimon/javacourse/lecture3/slides3.pdf

On a Windows system, the same call might return

c:\My Documents\java\lecture3\slides3.pdf

By manipulating File objects, you can do various things to files existing in the file system

Delete files (fil.delete(); fil.deleteOnExit(); )

Change the modification date/time fil.setLastModified(new Date().getTime());

Rename files ( fil.renameTo(“slides13.ps”); )

Page 27: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

java.io.Serializable

The interface java.io.Serializable allows writing objects to a (binary) stream:

public class Matrix implements Serializable { ...

Such objects are then read and written via ObjectInputStream and ObjectOutputStream objects, respectively:

try {

ObjectOutputStream oos = new

ObjectOutputStream(new FileWriter(“myfile.dat”));

oos.writeObject(this);

}

Page 28: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

java.io.Serializable

Serializing objects should be used with some caution, as the writeObject() method automatically includes all object references known to the object in question in the bytes to be written to the stream, thus introducing a lot of overhead

If at all in doubt, write your own text-based content-saving methods

Page 29: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

PlotDemo – this time with data loaded from disk

JButton

Click!

p(x)

FunctionPlotter(JFrame)

Polynomial

FileInput

paint()

coefficients

PolynomialGraph(JPanel)

Page 30: Events and Exceptionskom.aau.dk/~dimon/old-control-2016/teaching/ooslides6.pdf · 2009-09-24 · Events Events are similar to Exceptions, in that they are generated when “something

Classes (Objects) in PlotDemo

JButton

Click!

Polynomial

p(x)

FunctionPlotter(JFrame)

PolynomialGraph(JPanel)

NumericalInput

paint()

coefficients