Chapter 14 Exception Handling and Event Handling ISBN
Chapter 14 Exception Handling and Event Handling ISBN 0 -321 -33025 -0
Chapter 14 Topics • Introduction to Event Handling • Event Handling with Java • • Introduction to Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Copyright © 2006 Addison-Wesley. All rights reserved. 1 -2
Event Handling - Review • An event is created by an external action such as a user interaction through a GUI (compare to exceptions, which are often caused by code) • In conventional programming, order of execution is determined by code. In event-driven, order is determined by user. • The event is the notification that something has happened (an object) press key event an object event handler • The event handler is a segment of code that is called in response to an event Copyright © 2006 Addison-Wesley. All rights reserved. 1 -3
The Java Event Model • User interactions with GUI components create events that can be caught by event handlers, called event listeners • An event generator tells a listener of an event by sending a message (i. e. , calling a method) • An interface is used to make event-handling methods conform to a standard protocol • A class that implements a listener must include all required methods for the interface Copyright © 2006 Addison-Wesley. All rights reserved. 1 -4
Event Classes • Semantic Event Classes – Action. Event – Item. Event (item changed, user or pgm) – Text. Event (text has changed) • Lower-Level Event Classes – – – Component. Event (resize, hide, etc. ) Key. Event (key press) Mouse. Event (down, up) Mouse. Motion. Event Focus. Event (gain, lose focus) Copyright © 2006 Addison-Wesley. All rights reserved. 1 -5
Sample Keyboard Listener public class Game. Navigator extends Key. Adapter{ private Game. Draw gdraw; implements Key. Listener private JFrame gframe; // constructor method public Game. Navigator(JFrame gameframe, Game. Draw gamedraw ) { gdraw = gamedraw; // specific to our sample program gframe = gameframe; // Must add a Key. Listener and get the focus to respond // to keystrokes gframe. add. Key. Listener(this); gframe. request. Focus(); // VERY IMPORTANT to have focus } Copyright © 2006 Addison-Wesley. All rights reserved.
Sample Keyboard Listener (cont) public void key. Pressed(Key. Event e ) { int key. Code = e. get. Key. Code(); // update dir based on keypress switch ( key. Code ) { case Key. Event. VK_LEFT: // move left, Non-num Key LEFT gdraw. set. Direction("LEFT"); gdraw. set. Pos. X(gdraw. get. Pos. X()-10); break; case Key. Event. VK_RIGHT: // move right, Non-num Key RIGHT gdraw. set. Direction("RIGHT"); gdraw. set. Pos. X(gdraw. get. Pos. X()+10); break; case Key. Event. VK_UP: // move up, Non-num Key UP gdraw. set. Direction("UP"); gdraw. set. Pos. Y(gdraw. get. Pos. Y()-10); break; case Key. Event. VK_DOWN: // move down, Non-num Key DOWN gdraw. set. Direction("DOWN"); gdraw. set. Pos. Y(gdraw. get. Pos. Y()+10); break; } // end switch gdraw. update. Display(); // won’t see results if don’t redraw } Copyright © 2006 Addison-Wesley. All rights reserved.
Exception Handling issues • Hardware- and software- detectable exceptions • Exception handlers • Raising of exceptions • Binding of exceptions to handlers • Continuation • Default handlers • Exception disabling Copyright © 2006 Addison-Wesley. All rights reserved. 1 -8
Introduction to Exception Handling • In a language without exception handling – When an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated • In a language with exception handling – Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing Copyright © 2006 Addison-Wesley. All rights reserved. 1 -9
Exception Handling Alternatives • A language that does not have exception handling capabilities can still define, detect, raise, and handle exceptions (user defined, software detected) • Alternatives: – Send an auxiliary parameter or use the return value to indicate the return status of a subprogram. Caller must test the status. – Pass a label parameter to all subprograms (error return is to the passed label). Common in Fortran. – Pass an exception handling subprogram to all subprograms. Handler is called if exception occurs. Must be passed to every program. May need several handlers. Copyright © 2006 Addison-Wesley. All rights reserved. 1 -10
Basic Concepts - Review • An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing • The special processing that may be required after detection of an exception is called exception handling • The exception handling code unit is called an exception handler • An exception is raised/thrown when its associated event occurs • Many languages allow programs to trap input/output errors (including EOF) Copyright © 2006 Addison-Wesley. All rights reserved. 1 -11
Advantages of Built-in Exception Handling • Error detection code is tedious to write and it clutters the program • Exception propagation allows a high level of reuse of exception handling code • Encourage programmers to consider all events that could occur that might need to be handled. Copyright © 2006 Addison-Wesley. All rights reserved. 1 -12
Design Issues • How and where are exception handlers specified and what is their scope? • How is an exception occurrence bound to an exception handler? – If same exception can occur at different points in a unit, can it be bound to different handlers? – Is information about the exception made available to the exception handler? • Where does execution continue, if at all, after an exception handler completes its execution? – If error can be resolved, may return to statement that caused exception. – May specify finalization for subprogram. Copyright © 2006 Addison-Wesley. All rights reserved. 1 -13
Design Issues (continued) • How are user-defined exceptions specified? • Should there be default exception handlers for programs that do not provide their own? • Are there any built-in exceptions? • Can built-in exceptions be explicitly raised? • Are hardware-detectable errors treated as exceptions that can be handled? • How can exceptions be disabled, if at all? Copyright © 2006 Addison-Wesley. All rights reserved. 1 -14
Exception Handling Control Flow Copyright © 2006 Addison-Wesley. All rights reserved. 1 -15
Exception Handling in C++ • Added to C++ in 1990 • Design is based on that of CLU, Ada, and ML • Exceptions are user- or library-defined (none in language definition) Copyright © 2006 Addison-Wesley. All rights reserved. 1 -16
C++ Exception Handlers • Exception Handlers Form: try { -- code that is expected to raise an exception } catch (formal parameter) { // only 1 parm -- handler code }. . . catch (formal parameter) { -- handler code } Copyright © 2006 Addison-Wesley. All rights reserved. 1 -17
C++: The catch Function • catch is the name of all handlers--it is an overloaded name, so the formal parameter of each must be unique • The formal parameter need not have a variable – It can be simply a type name to distinguish the handler it is in from others • The formal parameter can be used to transfer information to the handler • The formal parameter can be an ellipsis, in which case it handles all exceptions not yet handled Copyright © 2006 Addison-Wesley. All rights reserved. 1 -18
C++: Throwing Exceptions • Exceptions are all raised explicitly by the statement: throw [expression]; • The brackets are metasymbols • A throw without an operand can only appear in a handler; when it appears, it simply re-raises the exception, which is then handled elsewhere • The type of the expression disambiguates the intended handler Copyright © 2006 Addison-Wesley. All rights reserved. 1 -19
Simple throw/catch example int num; char ch; double d. Num; try { cout << "Enter int from 1 - 100: "; cin >> num; if (num < 1 || num > 100) throw num; cout << "Enter 'A' or 'B' : "; cin >> ch; if (ch != 'A' && ch != 'B') throw ch; cout << "Enter double 1. 1 - 1. 5: "; cin >> d. Num; if (d. Num < 1. 1 || d. Num > 1. 5) throw d. Num; } Copyright © 2006 Addison-Wesley. All rights reserved. catch(int num. In) { cout << num. In << " is not in the rangen"; } catch (char. In) { cout << char. In << " is not A or Bn"; } catch (. . . ){ cout << "Invalid input!n"; } cout << "Continuing on. . . n";
C++: Unhandled Exceptions • An unhandled exception is propagated to the caller of the function in which it is raised • This propagation continues to the main function • If no matching handler is found through propagation, the default handler (unexpected) is called • The default handler simply terminates the program Copyright © 2006 Addison-Wesley. All rights reserved. 1 -21
C++: Continuation? • After a handler completes its execution, control flows to the first statement after the last handler in the sequence of handlers of which it is an element Copyright © 2006 Addison-Wesley. All rights reserved. 1 -22
Simple Propagation Example int do. Input(); int main() { int num; try { do. Input(); }catch(int num. In) { cout << num. In << " is not in the rangen"; system("pause"); exit(1); } cout << "Continuing on. . . n"; system("pause"); } Copyright © 2006 Addison-Wesley. All rights reserved. int do. Input() { int num; cout << "Enter a number from 1 - 100: "; cin >> num; if (num < 1 || num > 100) throw num; return num; }
C++: Other Design Choices • All exceptions are user-defined • Exceptions are neither specified nor declared • Functions can list the exceptions they may raise (but not required – unlike checked) • Without a specification, a function can raise any exception (the throw clause) • The default handler can be replaced by a user-defined handler. Must be a void function that takes no parameters. Copyright © 2006 Addison-Wesley. All rights reserved. 1 -24
C++: Evaluation • It is odd that exceptions are not named and that hardware- and system softwaredetectable exceptions cannot be handled • Binding exceptions to handlers through the type of the parameter certainly does not promote readability Copyright © 2006 Addison-Wesley. All rights reserved. 1 -25
C++ Exception Exercise • Do the Chapter 14 C++ Exercise Copyright © 2006 Addison-Wesley. All rights reserved.
C++ Exception Example // Grade. Distribution #include <iostream> using namespace std; // Exception to deal with end of data class Negative. Input. Exception { public: Negative. Input. Exception() { cout << "End of input" << endl; } }; // end Negative. Input. Exception class Copyright © 2006 Addison-Wesley. All rights reserved. 1 -27
C++ Exception Example (cont) int main() // Any exception can be raised{ int new_grade, index, limit_1, limit_2; int freq[10] = {0}; try { while (true) { cout << "Please input a grade or -1 to end: "; cin >> new_grade; if (new_grade < 0) // Terminating condition throw Negative. Input. Exception(); index = new_grade / 10; try { if (index > 9) throw new_grade; Not recommended technique freq[index]++; } Copyright © 2006 Addison-Wesley. All rights reserved. 1 -28
C++ Exception Example (cont) catch (int grade) { // Handler for index error if (grade == 100) freq[9]++; else cout << "Error: " << grade << " out of range!n"; } // end of catch(int grade) } // end of while } // end of outer try block catch (Negative. Input. Exception e) { // Handler for negative cout << "Limits Frequencyn"; for (index = 0; index < 10; index++) { limit_1 = 10 *index; limit_2 = limit_1 + 9; if (index == 9) limit_2 = 100; cout << limit_1 << " " << limit_2 << " " << freq[index] << endl; } // end for } // end catch (negative int) Copyright © 2006 Addison-Wesley. All rights reserved. } // end main 1 -29
Exception Handling in Java • Based on that of C++, but more in line with OOP philosophy • All exceptions are objects of classes that are descendants of the Throwable class Copyright © 2006 Addison-Wesley. All rights reserved. 1 -30
Java: Classes of Exceptions • The Java library includes two subclasses of Throwable: – Error • Thrown by the Java interpreter for events such as heap overflow • Never handled by user programs – Exception • User-defined exceptions are usually subclasses of this • Has two predefined subclasses, IOException and Runtime. Exception (e. g. , Array. Index. Out. Of. Bounds. Exception and Null. Pointer. Exception) Throwable: class with methods get. Cause, get. Message, print. Stack. Trace etc. Copyright © 2006 Addison-Wesley. All rights reserved. 1 -31
Java: Exception Handlers • Like those of C++, except every catch requires a named parameter and all parameters must be descendants of Throwable (e. g. , no ints or chars) • Syntax of try clause is exactly that of C++ • Exceptions are thrown with throw, as in C++, but often the throw includes the new operator to create the object, as in: throw new My. Exception(); Throw new My. Exception(“Bad input, dummy”); Copyright © 2006 Addison-Wesley. All rights reserved. 1 -32
Java: Binding Exceptions to Handlers • Exceptions are bound to the first handler with a parameter of the same class as the thrown object (or an ancestor of it) • An exception can be handled and rethrown by including a throw in the handler (a handler could also throw a different exception) • A handler can be written for Exception to catch all exceptions (place at end of list) Copyright © 2006 Addison-Wesley. All rights reserved. 1 -33
Java: Continuation? • If no handler is found in the try construct, the search is continued in the nearest enclosing try construct, etc. (i. e. , trys can be nested) • If no handler is found in the method, the exception is propagated to the method’s caller • If no handler is found (all the way to main), the program is terminated* * c++ has unexpected handler Copyright © 2006 Addison-Wesley. All rights reserved. 1 -34
Checked and Unchecked Exceptions • The Java throws clause is quite different from the throw clause of C++ • Exceptions of class Error and Run. Time. Exception and all of their descendants are called unchecked exceptions • All other exceptions are called checked exceptions (checked by compiler – all exceptions occur at runtime) • Checked exceptions that may be thrown by a method must be either: – Listed in the throws clause, or – Handled in the method What types of exceptions are normally checked? Copyright © 2006 Addison-Wesley. All rights reserved. 1 -35
Design Issues • A method cannot declare more exceptions in its throws clause than the method it overrides* • A method that calls a method that lists a particular checked exception in its throws clause has three alternatives for dealing with that exception: public void A() throws Bad. Exception { … } public void B() { … try { A() } catch (Bad. Exception e) { … } } public void C() throws An. Exception{ … try { A() } catch (Bad. Exception e) { throw (An. Exception) } } – Catch and handle the exception – Catch the exception and throw an exception that is listed in its own throws clause – Declare that exception in its throws public void D() throws Bad. Exception clause and do not handle it { … A() … } *Example: If you override run in a Thread class, you cannot add a throws clause Copyright © 2006 Addison-Wesley. All rights reserved. 1 -36
Java Exception Example import java. io. *; class Grade. Dist { int new. Grade, index, limit_1, limit_2; int [] freq = {0, 0, 0, 0}; void build. Dist() throws IOException { Data. Input. Stream in = new Data. Input. Stream(System. in); try { while (true) { new. Grade = Integer. parse. Int(in. read. Line()); if (new. Grade < 0) // Terminating condition throw new Negative. Input. Exception(); index = new. Grade / 10; try { freq[index]++; Copyright © 2006 Addison-Wesley. All rights reserved. 1 -37
Java Exception Example (cont) } catch (Array. Index. Out. Of. Bounds. Exception e) { if (new. Grade == 100) freq[9]++; else System. out. println("Error: " + new. Grade + " out of range!"); } // end of catch } // end of while } catch (Negative. Input. Exception e) { // Handler for negative System. out. println("Limits Frequency"); for (index = 0; index < 10; index++) { limit_1 = 10 *index; limit_2 = limit_1 + 9; if (index == 9) limit_2 = 100; System. out. println(limit_1 + " " + limit_2 + " " + freq[index]); } // end for } // end catch (negative int) } // end build. Dist Copyright © 2006 Addison-Wesley. All rights reserved. 1 -38
Java Exception Example (cont) class Negative. Input. Exception extends Exception { public Negative. Input. Exception() { System. out. println("End of input"); } } // end of Negative. Input. Exception class public static void main(String[] args) throws IOException { Grade. Dist dist = new Grade. Dist(); dist. build. Dist(); } // end main } // end class Copyright © 2006 Addison-Wesley. All rights reserved. 1 -39
Java: The finally Clause • Can appear at the end of a try construct • Form: finally {. . . } • Purpose: To specify code that is to be executed, regardless of what happens in the try construct (e. g. , to close file or database connection). Finally is executed even if there is a return statement in the block. Copyright © 2006 Addison-Wesley. All rights reserved. 1 -40
Java: Example • A try construct can be used with a finally clause try { for (index = 0; index < 100; index++) { … if (…) { return; } //** end of if } //** end of try clause finally { … } //** end of try construct Copyright © 2006 Addison-Wesley. All rights reserved. 1 -41
Java: Assertions • Statements in the program declaring a boolean expression regarding the current state of the computation • When evaluated to true nothing happens • When evaluated to false an Assertion. Error is thrown • Can be disabled during runtime without program modification or recompilation (java –da Program) • Often used for pre/post-condition testing • Two forms – assert condition; – assert condition: expression; Copyright © 2006 Addison-Wesley. All rights reserved. 1 -42
Assertion Example public class Test. Assertions { double balance; public Test. Assertions(double balance) { this. balance = balance; } public void withdraw(double amount) { assert (balance >= amount); balance -= amount; } public static void main(String[] args) { Test. Assertions ta = new Test. Assertions(10); try { ta. withdraw(15); } catch (Assertion. Error a) { System. out. println("You have committed a grave injustice!"); }}} Copyright © 2006 Addison-Wesley. All rights reserved.
Evaluation • Requring objects that extend Throwable is an improvement over C++, which allows any primitive type (not as readable). • The throws clause is better than that of C++ (The throw clause in C++ says little to the programmer) • The finally clause is often useful • The Java interpreter throws a variety of exceptions that can be handled by user programs Copyright © 2006 Addison-Wesley. All rights reserved. 1 -44
Summary • Ada provides extensive exception-handling facilities with a comprehensive set of built-in exceptions. • C++ includes no predefined exceptions. Exceptions are bound to handlers by connecting the type of expression in the throw statement to that of the formal parameter of the catch function • Java exceptions are similar to C++ exceptions except that a Java exception must be a descendant of the Throwable class. Additionally Java includes a finally clause • An event is a notification that something has occurred that requires handling by an event handler Copyright © 2006 Addison-Wesley. All rights reserved. 1 -45
Exercise • Review the following websites, and/or find some of your own that discuss good practices for Exception handling. • Be prepared to discuss your “top 3” – the practices/advice you think will be most useful. • Sites: – http: //www. ibm. com/developerworks/library/jejbexcept. html – http: //www. ibm. com/developerworks/java/library/jejb 01283. html – http: //today. java. net/pub/a/today/2003/12/04/exceptions. html – http: //www. onjava. com/pub/a/onjava/2003/11/19/excepti ons. html Copyright © 2006 Addison-Wesley. All rights reserved.
Event Handling Exercise • Download Tetris. Sample. jar • Run Sample. Key. Motion to see how the Tetris piece responds to keystrokes • Modify the program so the piece responds slightly differently (e. g. , moves farther for each keystroke) • You can also look at Sample. Motion to see how the piece can move by itself • Nothing to turn in, this is just to become familiar with or review event handling Copyright © 2006 Addison-Wesley. All rights reserved.
- Slides: 47