17
May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages Programming Languages (ICE 1341) (ICE 1341) Lecture #21 Lecture #21 May 21, 2004 In-Young Ko iko .AT. i cu . ac.kr Information and Communications University (ICU)

May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

Embed Size (px)

Citation preview

Page 1: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Programming LanguagesProgramming Languages(ICE 1341)(ICE 1341)

Lecture #21Lecture #21 May 21, 2004

In-Young Koiko .AT. icu.ac.kr

Information and Communications University (ICU)

Page 2: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 2 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

AnnouncementsAnnouncements

Project PresentationsProject Presentations Dater & Time: Thursday May 27Dater & Time: Thursday May 27thth, 7:30PM – 9:30PM, 7:30PM – 9:30PM 10 minutes10 minutes for each team (in English) for each team (in English)

Final ExamFinal Exam:: Dater & Time: Dater & Time: June 4, 2004 11:00AM-12:00PMJune 4, 2004 11:00AM-12:00PM A A hand-writtenhand-written cheat sheet is allowed cheat sheet is allowed Chapters that will be covered:Chapters that will be covered:

Chapter 8 – 11Chapter 8 – 11 Chapter 12 except 12.7, 12.8 and 12.9Chapter 12 except 12.7, 12.8 and 12.9 Chapter 13 except 13.7Chapter 13 except 13.7 Chapter 14Chapter 14

Page 3: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 3 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Review of the Previous LecturesReview of the Previous Lectures

SemaphoresSemaphores Synchronization ProblemsSynchronization Problems Dining Philosophers ProblemDining Philosophers Problem

MonitorsMonitors Message PassingMessage Passing Java ThreadsJava Threads Statement-Level ConcurrencyStatement-Level Concurrency

Page 4: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 4 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception HandlingException Handling

ExceptionException: An unexpected condition that is : An unexpected condition that is raised raised (thrown)(thrown) during program execution during program execution Hardware Detectable Exceptions: Hardware Detectable Exceptions: e.g., Floating-point overflow, I/O e.g., Floating-point overflow, I/O

errorserrors Software Detectable Exceptions: Software Detectable Exceptions: e.g., Array subscript range e.g., Array subscript range

errors, null pointer exceptionserrors, null pointer exceptions

EException xception HHandlingandling:: The special processing that may be The special processing that may be required after detection of an exception is calledrequired after detection of an exception is called

EException xception HHandlerandler: The exception handling : The exception handling code unitcode unit

OPEN (UNIT=10, FILE='data.txt', STATUS='OLD')OPEN (UNIT=10, FILE='data.txt', STATUS='OLD')30 READ(10, *, 30 READ(10, *, END=40END=40, , ERR=50ERR=50) NUM) NUM … … GOTO 30GOTO 30 FORTRAN

Page 5: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 5 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Handling ExampleException Handling Example

void fileCopy(String file1, String file2) {void fileCopy(String file1, String file2) { trytry { { FileInputStream in =FileInputStream in = new FileInputStream(file1)new FileInputStream(file1);; FileOutputStream out =FileOutputStream out = new FileOutputStream(file2)new FileOutputStream(file2);; int data;int data; while ((data = while ((data = in.read()in.read()) >= 0)) >= 0) out.write(data)out.write(data);; } } catchcatch ( (FileNotFoundExceptionFileNotFoundException e1) { e1) { System.err.printlnSystem.err.println (“Cannot open input or output file.”);(“Cannot open input or output file.”); } } catchcatch ( (IOExceptionIOException e2) { e2) { System.err.printlnSystem.err.println (“Cannot read or write data.”);(“Cannot read or write data.”); }}}}

May throw the May throw the File Not File Not FoundFound Exception Exception

May throw the May throw the IO IO ExceptionException

Exception HandlersException Handlers

Java

Page 6: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 6 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Descriptions in the Java Exception Descriptions in the Java API ManualAPI Manual

Page 7: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 7 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Handling Control FlowException Handling Control Flow

Main Program Main Program ControlControl

ExceptionException

Exception Exception HandlerHandler

ContinuationContinuation of the main of the main

programprogram

Catching the Catching the exceptionexception

Main Program Main Program ControlControl

ExceptionException

Operating Operating SystemSystem

Discontinuation Discontinuation of the main of the main

programprogram

Uncaught Uncaught exceptionexception

Page 8: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 8 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Advantages of Built-in Exception Advantages of Built-in Exception HandlingHandling

Programmers do not need to explicitly Programmers do not need to explicitly define, define, detect, detect, and and raise exceptionsraise exceptions

Exception propagation allows a high level of Exception propagation allows a high level of reuse of exception handling codereuse of exception handling code

* AW Lecture Notes

Page 9: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 9 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

ExceptionExceptionss in Java in Java

All exceptions are objectsAll exceptions are objects of classes that are of classes that are descendants of thedescendants of the ThrowableThrowable classclass

Serious problemsSerious problems that a that a user program should not user program should not

try to catchtry to catche.g., Heap overflowe.g., Heap overflow

MyIOExceptionMyIOException((User-defined ExceptionUser-defined Exception))

ErrorError

……

ExceptionException

IOExceptionIOException……

FileNotFoundExceptionFileNotFoundException……RunTimeExceptionRunTimeException

Unchecked ExceptionsUnchecked Exceptions• User programs are not User programs are not

required to handle themrequired to handle them• The compiler do not The compiler do not

concern themconcern them Checked ExceptionsChecked Exceptions

Program errorsProgram errorse.g., Array index e.g., Array index

out-of-bound, Null out-of-bound, Null pointer exceptionpointer exception

Page 10: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 10 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Handling in JavaException Handling in Java

Exceptions cannot be Exceptions cannot be disableddisabled

Binding Exceptions to Binding Exceptions to HandlersHandlers – – An exception An exception is bound to the first is bound to the first handler with a parameter handler with a parameter is the is the same class as the same class as the thrown object or an thrown object or an ancestor of itancestor of it

SSpecify code that is to be pecify code that is to be executed, regardless of executed, regardless of what happens in the try what happens in the try constructconstruct

void fileCopy(String file1, String file2) {void fileCopy(String file1, String file2) { trytry { { FileInputStream in =FileInputStream in = new FileInputStream(file1);new FileInputStream(file1); FileOutputStream out =FileOutputStream out = new FileOutputStream(file2);new FileOutputStream(file2); int data;int data; while ((data = in.read()) >= 0)while ((data = in.read()) >= 0) out.write(data);out.write(data); } } catchcatch ( (FileNotFoundExceptionFileNotFoundException e1) { e1) { System.err.println(“Can’t open a file.”);System.err.println(“Can’t open a file.”); } } catchcatch ( (IOExceptionIOException e2) { e2) { System.err.println(“Can’t read or System.err.println(“Can’t read or write.”);write.”); } } finallyfinally { { in.close();in.close(); out.close();out.close(); }}}}

Page 11: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 11 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Propagation in JavaException Propagation in Java

A method can be declared to A method can be declared to propagate certain exceptions propagate certain exceptions to its callerto its caller by using ‘ by using ‘throwsthrows’’

Exceptions are Exceptions are dynamically dynamically boundbound to handlers to handlers

To insure that all exceptions To insure that all exceptions are caught, a handler can be are caught, a handler can be defined to havedefined to have an an ExceptionException class parameter class parameter

There are built-in operations There are built-in operations in exception objectsin exception objects

void fileCopy(String file1, String file2) void fileCopy(String file1, String file2) throwsthrows FileNotFoundException, FileNotFoundException,

IOException IOException {{ FileInputStream in =FileInputStream in = new FileInputStream(file1);new FileInputStream(file1); FileOutputStream out =FileOutputStream out = new FileOutputStream(file2);new FileOutputStream(file2); int data;int data; while ((data = in.read()) >= 0)while ((data = in.read()) >= 0) out.write(data);out.write(data); in.close(); out.close();in.close(); out.close();}}void myMain() {void myMain() { trytry { { fileCopy (“source.txt”, “dest.txt”);fileCopy (“source.txt”, “dest.txt”); } } catchcatch ( (ExceptionException e) { e) { e.e.printStackTrace()printStackTrace();; }}}}

Page 12: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 12 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Stack Trace in JavaException Stack Trace in Java

Java’s exception stack trace shows the Java’s exception stack trace shows the dynamic chain of exception propagationsdynamic chain of exception propagations

java.io.FileNotFoundExceptionjava.io.FileNotFoundException: source.txt (The system : source.txt (The system cannot find the file specified)cannot find the file specified)

at at java.io.FileInputStream.openjava.io.FileInputStream.open(Native Method)(Native Method)

at at java.io.FileInputStreamjava.io.FileInputStream.<init>(Unknown Source).<init>(Unknown Source)

at at java.io.FileInputStreamjava.io.FileInputStream.<init>(Unknown Source).<init>(Unknown Source)

at ExceptionTest.at ExceptionTest.fileCopyfileCopy(ExceptionTest.java:(ExceptionTest.java:99))

at ExceptionTest.at ExceptionTest.myMainmyMain(ExceptionTest.java:(ExceptionTest.java:2020))

at ExceptionTest.at ExceptionTest.mainmain(ExceptionTest.java:(ExceptionTest.java:3030))

Page 13: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 13 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

User-defined Exceptions in JavaUser-defined Exceptions in Java

User-defined exceptionsUser-defined exceptions can be thrown by can be thrown by throwthrow

Rethrowing (reraising)Rethrowing (reraising) an exceptionan exception

void fileCopy(String file1, String file2) void fileCopy(String file1, String file2) throws throws MyIOException MyIOException {{ try {try { FileInputStream in =FileInputStream in = new FileInputStream(file1);new FileInputStream(file1); FileOutputStream out =FileOutputStream out = new FileOutputStream(file2);new FileOutputStream(file2); int data;int data; while ((data = in.read()) >= 0)while ((data = in.read()) >= 0) out.write(data);out.write(data); in.close(); out.close();in.close(); out.close(); } catch (Exception e) {} catch (Exception e) { throw new MyIOException()throw new MyIOException();; }}}}

Page 14: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 14 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Handling in Ada (1)Exception Handling in Ada (1)

Exception handlers are bound for program blocks:Exception handlers are bound for program blocks:beginebegine -- block body-- block body exceptionexception whenwhen exception_name exception_name {{ || exception_nameexception_name } } =>=>

statement_sequencestatement_sequence whenwhen ... ... [[when others =>when others => statement_sequence] statement_sequence]end;end;

User-defined Exceptions:User-defined Exceptions:exception_name_listexception_name_list : : exceptionexception;;raiseraise [exception_name] [exception_name]

Exception conditions can be disabledException conditions can be disabled with with (‘pragma’ is a (‘pragma’ is a directive to the compiler)directive to the compiler)::pragma SUPPRESSpragma SUPPRESS(exception_list)(exception_list)

Page 15: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 15 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Handling in Ada (2)Exception Handling in Ada (2)

Predefined Exceptions:Predefined Exceptions: CONSTRAINT_ERRORCONSTRAINT_ERROR - index constraints, range - index constraints, range

constraints, etc.constraints, etc. NUMERIC_ERRORNUMERIC_ERROR - numeric operation cannot - numeric operation cannot

return a correct value (overflow, division by zero, return a correct value (overflow, division by zero, etc.)etc.)

PROGRAM_ERRORPROGRAM_ERROR - call to a subprogram whose - call to a subprogram whose body has not been elaboratedbody has not been elaborated

STORAGE_ERRORSTORAGE_ERROR - system runs out of heap - system runs out of heap TASKING_ERRORTASKING_ERROR - an error associated with tasks - an error associated with tasks

* AW Lecture Notes

Page 16: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 16 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Exception Handling in C++Exception Handling in C++

Exceptions are bound to handlers through the Exceptions are bound to handlers through the type of the parametertype of the parameter:: int new_grade;int new_grade; trytry { if (index < 0 || index > 9) { if (index < 0 || index > 9) throwthrow (new_grade); … (new_grade); … } } catchcatch (int grade) { (int grade) { if (grade == 100) …if (grade == 100) … }}

All exceptions are user-definedAll exceptions are user-defined A A throwthrow without an operand without an operand can only appear in can only appear in

a handler; when it appears, it simply a handler; when it appears, it simply reraises reraises the exceptionthe exception, which is then handled elsewhere, which is then handled elsewhere

Page 17: May 21, 2004 1 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)

May 21, 2004 17 ICE 1341 – Programming Languages (Lecture #21) In-Young Ko

Event Handling in JavaEvent Handling in Java

An An eventevent is created by an external action such is created by an external action such as a user interaction through a GUIas a user interaction through a GUI

The The event handlerevent handler is a segment of code that is is a segment of code that is called in response to an eventcalled in response to an event

JButton helloButton = new JButton(“Hello”);JButton helloButton = new JButton(“Hello”); helloButtonhelloButton..addActionListeneraddActionListener(new AbstractAction() {(new AbstractAction() {

public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { System.out.println(“Hello World!”);System.out.println(“Hello World!”); }} }}

A JButtonA JButtonEEvent vent ListenersListeners

Button Pressed EventButton Pressed Event