Download presentation
Presentation is loading. Please wait.
Published byZion Kelp Modified over 9 years ago
1
ICE1341 Programming Languages Spring 2005 Lecture #20 & 21 Lecture #20 & 21 In-Young Ko iko.AT. icu.ac.kr iko.AT. icu.ac.kr Information and Communications University (ICU)
2
Spring 2005 2 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Announcements Project Presentation Sessions (May 26 th ) Project Presentation Sessions (May 26 th ) 7 minutes for each team (in English) 7 minutes for each team (in English) Explain design goals of your team Explain design goals of your team Show a sample program (XML and Target languages) Show a sample program (XML and Target languages) Discussions Discussions Language design decisions that made it easy and efficient to implement the cross compiler Language design decisions that made it easy and efficient to implement the cross compiler Language design decisions that made it difficult to implement the cross compiler Language design decisions that made it difficult to implement the cross compiler Please send me (iko.AT. icu.ac.kr) your presentation file (PPT files) by noon on May 26 th Please send me (iko.AT. icu.ac.kr) your presentation file (PPT files) by noon on May 26 th
3
Spring 2005 3 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Announcements Final Exam: Final Exam: Dater & Time: Monday May 30, 2005 4:00PM-6:00PM Dater & Time: Monday May 30, 2005 4:00PM-6:00PM Allowed to bring a hand-written ‘cheat sheet’ (A4 size, double-sided) Allowed to bring a hand-written ‘cheat sheet’ (A4 size, double-sided) Covering: Covering: Chapter 7 – 11 Chapter 7 – 11 Chapter 12 except 12.7, 12.8 and 12.9 Chapter 12 except 12.7, 12.8 and 12.9 Chapter 13 except 13.7 Chapter 13 except 13.7 Chapter 14 Chapter 14
4
Spring 2005 4 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Object-oriented Programming Languages Object-oriented Programming Languages Software Reuse Software Reuse Overriden Methods Overriden Methods Abstract Classes and Methods Abstract Classes and Methods Design Issues for OOPLs Design Issues for OOPLs Exclusive use of objects in typing systems Exclusive use of objects in typing systems Subclsses as subtypes Subclsses as subtypes Polymorphism and dynamic type checking Polymorphism and dynamic type checking Multiple inheritance Multiple inheritance Object allocation and deallocation mechanisms Object allocation and deallocation mechanisms Object-oriented Processing of XML Data Object-oriented Processing of XML Data Last Lecture
5
Spring 2005 5 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University This Lecture Concurrency Concurrency Categories of Concurrency Categories of Concurrency Semaphores Semaphores Exception Handling Exception Handling Exception Handling in Java Exception Handling in Java Exception Handling in Ada Exception Handling in Ada Event Handling in Java Event Handling in Java
6
Spring 2005 6 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Chapter 13 Concurrency
7
Spring 2005 7 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Concurrency “A program is said to be concurrent if it contains more than one active execution context” [M. Scott] “A program is said to be concurrent if it contains more than one active execution context” [M. Scott] void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("A"); sleep(0,1); try { System.out.print("A"); sleep(0,1); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("B"); sleep(0,1); try { System.out.print("B"); sleep(0,1); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();} Java Forking two concurrent execution threads Main Program Control Printing “A” Printing “B”
8
Spring 2005 8 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Categories of Concurrency Thread of control: A sequence of program points reached as control flows through the program Thread of control: A sequence of program points reached as control flows through the program Categories of Concurrency: Categories of Concurrency: Physical concurrency: Concurrency supported multiple independent processors Physical concurrency: Concurrency supported multiple independent processors Logical concurrency: Concurrency presented by time-sharing one processor (software can be designed as if there were multiple threads of control) Logical concurrency: Concurrency presented by time-sharing one processor (software can be designed as if there were multiple threads of control) Coroutines provide only quasi-concurrency Coroutines provide only quasi-concurrency * AW Lecture Notes
9
Spring 2005 9 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Subprogram-Level Concurrency (1) Task (Process): A program unit that can be in concurrent execution with other program units Task (Process): A program unit that can be in concurrent execution with other program units Tasks differ from ordinary subprograms in that: A task may be implicitly started When a program unit starts the execution of a task, the program is not necessarily suspended When a task’s execution is completed, control may not return to the caller void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("A"); try { System.out.print("A"); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { while (true) { while (true) { try { System.out.print("B"); try { System.out.print("B"); } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();}
10
Spring 2005 10 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Subprogram-Level Concurrency (2) A task is disjoint if it does not communicate with or affect the execution of any other task in the program in any way A task is disjoint if it does not communicate with or affect the execution of any other task in the program in any way Task communication is necessary for synchronization Task communication is necessary for synchronization Shared nonlocal variables Shared nonlocal variables Parameters Parameters Message passing Message passing Race Condition: a situation in which more than one tasks are racing to use shared resources Race Condition: a situation in which more than one tasks are racing to use shared resources int count = 0; void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("A"); System.out.print("A"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("B"); System.out.print("B"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();}
11
Spring 2005 11 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Subprogram-Level Concurrency Race Condition: a situation in which more than one tasks are racing to use shared resources Race Condition: a situation in which more than one tasks are racing to use shared resources int count = 0; void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("A"); System.out.print("A"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (count++ < 20) { try { while (count++ < 20) { System.out.print("B"); System.out.print("B"); sleep(0, 1); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();} A BAB count < 20 T count++ count = 19 count = 21 count < 20 T count++ print one more character
12
Spring 2005 12 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Semaphores – Dijkstra 1965 class Semaphore { int s = 0; int s = 0; public synchronized void p() { public synchronized void p() { while (s < 0) continue; while (s < 0) continue; s--; s--; } public synchronized void v() { public synchronized void v() { s++; s++; }} int count = 0; Semaphore sem = new Semaphore(); void concurrentPrint() { (new Thread () { public void run() { (new Thread () { public void run() { try { while (true) { try { while (true) { sem.p(); // wait sem.p(); // wait if (count++ < 20) if (count++ < 20) { System.out.print("A"); sleep(0, 1); } sem.v(); // release sem.v(); // release } } catch (Exception e) { } } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { public void run() { (new Thread () { public void run() { try {while (true) { try {while (true) { sem.p(); // wait sem.p(); // wait if (count++ < 20) if (count++ < 20) { System.out.print(“B"); sleep(0, 1); } sem.v(); // release sem.v(); // release } } catch (Exception e) { } } } catch (Exception e) { } } }).start(); }).start();} Semaphore: a data structure consisting of a counter and a queue for storing task descriptors Guarded code Guarded code
13
Spring 2005 13 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Synchronization Problems Cooperation Synchronization: synchronization in counting something Cooperation Synchronization: synchronization in counting something e.g., The previous example of sharing a counter, Sharing a buffer by a producer and a consumer Competition Synchronization: synchronization in sharing a resource Competition Synchronization: synchronization in sharing a resource e.g., Dining Philosophers problem Peterson & Silberschatz
14
Spring 2005 14 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Dining Philosophers Problem Peterson & Silberschatz Five philosophers spend their lives thinking and eating Five philosophers spend their lives thinking and eating The philosophers share a circular table The philosophers share a circular table In the center of the table, there is a bowl of rice In the center of the table, there is a bowl of rice The table is laid with five chopsticks The table is laid with five chopsticks When a philosopher gets hungry, he tries to pickup two chopsticks that are closest to him When a philosopher gets hungry, he tries to pickup two chopsticks that are closest to him Dijstra 1965
15
Spring 2005 15 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Solving The Dining Philosophers Problem Using Semaphores Peterson & Silberschatz Semaphore[] chopsticks = new Semaphore[5]; chopsticks = new Semaphore[5]; chopsticks[0] = new Semaphore(); … while (true) { chopsticks[i].p(); chopsticks[i].p(); chopsticks[(i+1) % 5].p(); chopsticks[(i+1) % 5].p();… // eat … chopsticks[i].v(); chopsticks[i].v(); chopsticks[(i+1) % 5].v(); chopsticks[(i+1) % 5].v();… // think …} 0 1 2 3 4 0 1 2 3 4
16
Spring 2005 16 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Evaluation of Semaphores Misuse of semaphores (when a P operation is left out) can cause failures in cooperation synchronization Misuse of semaphores (when a P operation is left out) can cause failures in cooperation synchronization e.g., out of index, buffer overflow Misuse of semaphores (when a V operation is left out) can cause failures in competition synchronization Misuse of semaphores (when a V operation is left out) can cause failures in competition synchronization e.g., infinite loop, deadlock
17
Spring 2005 17 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Synchronized Objects int count = 0; Object s = new Object(); void concurrentPrint() { (new Thread () { (new Thread () { public void run() { public void run() { try { while (true) { try { while (true) { synchronized(s) { synchronized(s) { if (count++ >= 20) break; } System.out.print("A"); sleep(0, 1); System.out.print("A"); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (true) { try { while (true) { synchronized(s) { synchronized(s) { if (count++ >= 20) break; } System.out.print("B"); sleep(0, 1); System.out.print("B"); sleep(0, 1); } } catch (Exception e) { } } catch (Exception e) { } } }).start(); }).start();} Java Only the thread that owns the semaphore object can execute the guarded code
18
Spring 2005 18 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Monitors public class PrintAB { int count = 0; int count = 0; public synchronized boolean printA() { public synchronized boolean printA() { if (count++ < 20) { if (count++ < 20) {System.out.print(“A”); return true; } return false; return false; } public synchronized boolean printB() { public synchronized boolean printB() { if (count++ < 20) { if (count++ < 20) {System.out.print(“B”); return true; } return false; return false; }}… void concurrentPrint() { final PrintAB prtJob = new PrintAB(); final PrintAB prtJob = new PrintAB(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (prtJob.printA()) try { while (prtJob.printA()) sleep(0, 1); sleep(0, 1); } catch(Exception e) { … } } catch(Exception e) { … } } }).start(); }).start(); (new Thread () { (new Thread () { public void run() { public void run() { try { while (prtJob.printB()) try { while (prtJob.printB()) sleep(0, 1); sleep(0, 1); } catch(Exception e) { … } } catch(Exception e) { … } } }).start(); }).start();}
19
Spring 2005 19 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Monitors – Hoare 1974 Encapsulation of shared data structures for semaphores with their operations and hide their representations Encapsulation of shared data structures for semaphores with their operations and hide their representations Access to the shared data in the monitor is limited to a single process at a time Access to the shared data in the monitor is limited to a single process at a time Multiple calls are queued Multiple calls are queued e.g., Concurrent Pascal, Modula, Mesa, Java (objects can be used as monitors) e.g., Concurrent Pascal, Modula, Mesa, Java (objects can be used as monitors) public class PrintAB { int count = 0; int count = 0; public synchronized boolean printA() { public synchronized boolean printA() { if (count++ < 20) { if (count++ < 20) {System.out.print(“A”); return true; } return false; return false; } public synchronized boolean printB() { public synchronized boolean printB() { if (count++ < 20) { if (count++ < 20) {System.out.print(“B”); return true; } return false; return false; }}
20
Spring 2005 20 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University A Monitor Example Cooperation synchronization using a monitor Cooperation synchronization using a monitor Shared bounded buffer (queue) problem Shared bounded buffer (queue) problem
21
Spring 2005 21 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University A Monitor Example public class BoundedBuffer { int size = 100; int size = 100; int[] buf = new int[size]; int[] buf = new int[size]; int front = 0, rear = 0, count = 0; int front = 0, rear = 0, count = 0; public synchronized void insert(int data) { public synchronized void insert(int data) { throws InterruptedException { throws InterruptedException { if (count == size) wait(); if (count == size) wait(); buf[rear] = data; buf[rear] = data; rear = (rear + 1) % size; count++; rear = (rear + 1) % size; count++; if (count == 1) notify(); if (count == 1) notify(); } public synchronized int remove() { public synchronized int remove() { throws InterruptedException{ throws InterruptedException{ if (count == 0) wait(); if (count == 0) wait(); int result = buf[front]; int result = buf[front]; front = (front+1) % size; count--; front = (front+1) % size; count--; if (count == size-1) notify(); if (count == size-1) notify(); return result; return result; }} Producer threads call ‘insert’ to add data Producer threads call ‘insert’ to add data Consumer threads call ‘remove’ to fetch data Consumer threads call ‘remove’ to fetch data Causes the current thread to wait until another thread invokes ‘notify’ Wakes up a thread that is waiting on this object’s monitor
22
Spring 2005 22 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Evaluation of Monitors Support for competition synchronization is great Support for competition synchronization is great Support for cooperation synchronization is very similar as with semaphores, so it has the same problems Support for cooperation synchronization is very similar as with semaphores, so it has the same problems
23
Spring 2005 23 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Message Passing A message Tasks are distributed across different programs and/or different machines
24
Spring 2005 24 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Message Passing Models A way to handle the problem of synchronizing program units in a distributed system A way to handle the problem of synchronizing program units in a distributed system Synchronous Message Passing Model: A task is blocked until its counterpart accepts a message Synchronous Message Passing Model: A task is blocked until its counterpart accepts a message Rendezvous: A message transmission when a sender task’s message is accepted by a receiver task Rendezvous: A message transmission when a sender task’s message is accepted by a receiver task Asynchronous Message Passing Model: A task proceeds its execution after sending a message to its counterpart Asynchronous Message Passing Model: A task proceeds its execution after sending a message to its counterpart A sender must know the entry name of the receiver, but not vice versa (asymmetric) A sender must know the entry name of the receiver, but not vice versa (asymmetric)
25
Spring 2005 25 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University A Message Passing Example … try { ServerSocket s = new ServerSocket(80); ServerSocket s = new ServerSocket(80); while (true) { while (true) { Socket incoming = s.accept(); Socket incoming = s.accept(); InputStream in = incoming.getInputStream(); InputStream in = incoming.getInputStream(); createThreadToProcessCommand(in); createThreadToProcessCommand(in); …. …. } } catch (Exception e) { … } … try { Socket s = new Socket(“www.icu.ac.kr”, 80); Socket s = new Socket(“www.icu.ac.kr”, 80); OutputStream out = s.getOutputStream(); OutputStream out = s.getOutputStream(); InputStream in = s.getInputStream(); InputStream in = s.getInputStream(); createThreadToSendCommand(out); createThreadToSendCommand(out); createThreadToReceiveResults(in); createThreadToReceiveResults(in); … } catch (Exception e) { … } Rendezvous HTTP Server (Web Server) HTTP Client Entry Name
26
Spring 2005 26 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Rendezvous Time Lines
27
Spring 2005 27 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Java Threads Java threads are lightweight tasks – all threads run in the same address space Java threads are lightweight tasks – all threads run in the same address space c.f., Ada tasks are heavyweight threads (processes) that run in their own address spaces c.f., Ada tasks are heavyweight threads (processes) that run in their own address spaces class MyThread extends Thread { public void run() { public void run() { … // Task body // Task body … }}… Thread aTask = new MyThread(); aTask.start(); … aTask.setPriority (Thread.MAX_PRIORITY); (Thread.MAX_PRIORITY);… aTask.join(); … Controls the thread scheduler Waits for the thread to complete
28
Spring 2005 28 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Statement-Level Concurrency High-Performance Fortran (HPF) High-Performance Fortran (HPF) The compiler maps a program onto a multiprocessor architecture The compiler maps a program onto a multiprocessor architecturee.g., REAL list_1(1000), list_2(1000) INTEGER list_3(500), list_4(501) !HPF$ PROCESSORS proc (10) !HPF$ DISTRIBUTE (BLOCK) ONTO procs :: list_1, list_2 !HPF$ ALIGN list_1(index) WITH list_4 (index+1) … list_1 (index) = list_2(index) list_1 (index) = list_2(index) list_3(index) = list_4(index+1) list_3(index) = list_4(index+1) … FORALL (index = 1:1000) list_1(index) = list_2(index) * 1.2 list_1(index) = list_2(index) * 1.2
29
Spring 2005 29 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Chapter 14 Exception Handling and Event
30
Spring 2005 30 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling Exception: An unexpected condition that is raised (thrown) during program execution Exception: An unexpected condition that is raised (thrown) during program execution Hardware Detectable Exceptions: e.g., Floating-point overflow, I/O errors Hardware Detectable Exceptions: e.g., Floating-point overflow, I/O errors Software Detectable Exceptions: e.g., Array subscript range errors, null pointer exceptions Software Detectable Exceptions: e.g., Array subscript range errors, null pointer exceptions Exception Handling: The special processing that may be required after detection of an exception is called Exception Handling: The special processing that may be required after detection of an exception is called Exception Handler: The exception handling code unit Exception Handler: The exception handling code unit OPEN (UNIT=10, FILE='data.txt', STATUS='OLD') OPEN (UNIT=10, FILE='data.txt', STATUS='OLD') 30 READ(10, *, END=40, ERR=50) NUM … GOTO 30 GOTO 30 FORTRAN
31
Spring 2005 31 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling Example void fileCopy(String file1, String file2) { 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); } catch (FileNotFoundException e1) { } catch (FileNotFoundException e1) { System.err.println System.err.println (“Cannot open input or output file.”); (“Cannot open input or output file.”); } catch (IOException e2) { } catch (IOException e2) { System.err.println System.err.println (“Cannot read or write data.”); (“Cannot read or write data.”); }} May throw the File Not Found Exception May throw the IO Exception Exception Handlers Java
32
Spring 2005 32 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Descriptions in the Java API Manual
33
Spring 2005 33 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling Control Flow Main Program Control Exception Exception Handler Continuation of the main program Catching the exception Main Program Control Exception Operating System Discontinuation of the main program Uncaught exception
34
Spring 2005 34 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Advantages of Built-in Exception Handling Programmers do not need to explicitly define, detect, and raise exceptions Programmers do not need to explicitly define, detect, and raise exceptions Exception propagation allows a high level of reuse of exception handling code Exception propagation allows a high level of reuse of exception handling code * AW Lecture Notes
35
Spring 2005 35 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exceptions in Java All exceptions are objects of classes that are descendants of the Throwable class All exceptions are objects of classes that are descendants of the Throwable class Serious problems that a user program should not try to catch e.g., Heap overflow MyIOException (User-defined Exception) Error … Exception IOException … FileNotFoundException… RunTimeException Unchecked Exceptions User programs are not required to handle themUser programs are not required to handle them The compiler do not concern themThe compiler do not concern them Checked Exceptions Program errors e.g., Array index out-of-bound, Null pointer exception
36
Spring 2005 36 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in Java Exceptions cannot be disabled Exceptions cannot be disabled Binding Exceptions to Handlers – An exception is bound to the first handler with a parameter is the same class as the thrown object or an ancestor of it Binding Exceptions to Handlers – An exception is bound to the first handler with a parameter is the same class as the thrown object or an ancestor of it Specify code that is to be executed, regardless of what happens in the try construct Specify code that is to be executed, regardless of what happens in the try construct void fileCopy(String file1, String file2) { 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); } catch (FileNotFoundException e1) { } catch (FileNotFoundException e1) { System.err.println(“Can’t open a file.”); System.err.println(“Can’t open a file.”); } catch (IOException e2) { } catch (IOException e2) { System.err.println(“Can’t read or write.”); System.err.println(“Can’t read or write.”); } finally { } finally { in.close(); in.close(); out.close(); out.close(); }}
37
Spring 2005 37 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Propagation in Java A method can be declared to propagate certain exceptions to its caller by using ‘throws’ A method can be declared to propagate certain exceptions to its caller by using ‘throws’ Exceptions are dynamically bound to handlers Exceptions are dynamically bound to handlers To insure that all exceptions are caught, a handler can be defined to have an Exception class parameter To insure that all exceptions are caught, a handler can be defined to have an Exception class parameter There are built-in operations in exception objects There are built-in operations in exception objects void fileCopy(String file1, String file2) throws FileNotFoundException, throws 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() { try { try { fileCopy (“source.txt”, “dest.txt”); fileCopy (“source.txt”, “dest.txt”); } catch (Exception e) { } catch (Exception e) { e.printStackTrace(); e.printStackTrace(); }}
38
Spring 2005 38 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Stack Trace in Java Java’s exception stack trace shows the dynamic chain of exception propagations Java’s exception stack trace shows the dynamic chain of exception propagations java.io.FileNotFoundException: source.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream. (Unknown Source) at ExceptionTest.fileCopy(ExceptionTest.java:9) at ExceptionTest.myMain(ExceptionTest.java:20) at ExceptionTest.main(ExceptionTest.java:30)
39
Spring 2005 39 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University User-defined Exceptions in Java User-defined exceptions can be thrown by throw User-defined exceptions can be thrown by throw Rethrowing (reraising) an exception Rethrowing (reraising) an exception void fileCopy(String file1, String file2) throws MyIOException { throws 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(); }}
40
Spring 2005 40 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in Ada (1) Exception handlers are bound for program blocks: Exception handlers are bound for program blocks:begine -- block body -- block body exception exception when exception_name { | exception_name } => statement_sequence when exception_name { | exception_name } => statement_sequence when... when... [when others => statement_sequence] [when others => statement_sequence]end; User-defined Exceptions: User-defined Exceptions: exception_name_list : exception; raise [exception_name] Exception conditions can be disabled with (‘pragma’ is a directive to the compiler): Exception conditions can be disabled with (‘pragma’ is a directive to the compiler): pragma SUPPRESS(exception_list)
41
Spring 2005 41 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in Ada (2) Predefined Exceptions: Predefined Exceptions: CONSTRAINT_ERROR - index constraints, range constraints, etc. CONSTRAINT_ERROR - index constraints, range constraints, etc. NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by zero, etc.) NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by zero, etc.) PROGRAM_ERROR - call to a subprogram whose body has not been elaborated PROGRAM_ERROR - call to a subprogram whose body has not been elaborated STORAGE_ERROR - system runs out of heap STORAGE_ERROR - system runs out of heap TASKING_ERROR - an error associated with tasks TASKING_ERROR - an error associated with tasks * AW Lecture Notes
42
Spring 2005 42 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exception Handling in C++ Exceptions are bound to handlers through the type of the parameter: Exceptions are bound to handlers through the type of the parameter: int new_grade; int new_grade; try { if (index 9) try { if (index 9) throw (new_grade); … throw (new_grade); … } catch (int grade) { } catch (int grade) { if (grade == 100) … if (grade == 100) … } All exceptions are user-defined All exceptions are user-defined A throw without an operand can only appear in a handler; when it appears, it simply reraises the exception, which is then handled elsewhere A throw without an operand can only appear in a handler; when it appears, it simply reraises the exception, which is then handled elsewhere
43
Spring 2005 43 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Event Handling in Java An event is created by an external action such as a user interaction through a GUI An event is created by an external action such as a user interaction through a GUI The event handler is a segment of code that is called in response to an event The event handler is a segment of code that is called in response to an event JButton helloButton = new JButton(“Hello”); JButton helloButton = new JButton(“Hello”); helloButton.addActionListener(new AbstractAction() { helloButton.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { System.out.println(“Hello World!”); System.out.println(“Hello World!”); } } A JButton Event Listeners Button Pressed Event
44
Spring 2005 44 ICE 1341 – Programming Languages © In-Young Ko, Information and Communications University Exercises for the Final Exam Problems in the text book Problems in the text book Chapter 7 – Problem Set #13 Chapter 7 – Problem Set #13 Chapter 8 – Review Questions #5, 8 Chapter 8 – Review Questions #5, 8 Chapter 9 – Problem Set #5 Chapter 9 – Problem Set #5 Chapter 10 – Problem Set #2 Chapter 10 – Problem Set #2 Chapter 11 – Problem Set #3 Chapter 11 – Problem Set #3 Chapter 12 – Problem Set #1, 2 Chapter 12 – Problem Set #1, 2 Chapter 13 – Problem Set #6, 9 (Explain the reason or prove it by writing a sample Java program) Chapter 13 – Problem Set #6, 9 (Explain the reason or prove it by writing a sample Java program)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.