ISBN 0-321-49362-1 Chapter 14 Exception Handling and Event Handling.

Slides:



Advertisements
Similar presentations
Exception Handling and Event Handling
Advertisements

Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 13 In a language without exception handling: When an exception occurs, control goes to the operating.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Chapter 14 Exception Handling and Event Handling.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
ISBN Chapter 14 Exception Handling and Event Handling.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Chapter 11 Exception Handling and Event Handling.
ISBN Chapter 14 Exception Handling and Event Handling.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Chapter 13, Slide 1 Exception Handling Exception handling is a language feature that allows the programmer to handle runtime "exceptional conditions."
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
May 21, ICE 1341 – Programming Languages (Lecture #21) In-Young Ko Programming Languages (ICE 1341) Lecture #21 Programming Languages (ICE 1341)
Chapter 14 Exception Handling and Event Handling.
Object Oriented Programming
ISBN Chapter 14 Exception Handling and Event Handling.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
COMP Exception Handling Yi Hong June 10, 2015.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
ISBN Chapter 14 Exception Handling and Event Handling.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Exceptions and Assertions Chapter 15 – CSCI 1302.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
1 Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Exceptions in the Java programming language J. W. Rider.
Java Exceptions a quick review….
Exception Handling C++.
Exception Handling and Event Handling
Exception Handling and Event Handling
Exception and Event Handling
Java Programming Language
Exception Handling and Event Handling
Exception Handling and Event Handling
Exception Handling Chapter 9 Edited by JJ.
Exception Handling In Text: Chapter 14.
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exception Handling and Event Handling
Exception Handling and Event Handling
Exception and Event Handling
Exception Handling and Event Handling
Java Basics Exception Handling.
Exception Handling and Event Handling
Exception Handling.
Presentation transcript:

ISBN Chapter 14 Exception Handling and Event Handling

Copyright © 2015 Pearson. All rights reserved.1-2 Chapter 14 Topics Introduction to Exception Handling Exception Handling in C++ Exception Handling in Java Exception Handling in Python and Ruby Introduction to Event Handling Event Handling with Java Event Handling in C#

Copyright © 2015 Pearson. All rights reserved.1-3 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 © 2015 Pearson. All rights reserved.1-4 Basic Concepts Many languages allow programs to trap input/output errors (including EOF) 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

Copyright © 2015 Pearson. All rights reserved.1-5 Exception Handling Alternatives An exception is raised when its associated event occurs 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 –Pass a label parameter to all subprograms (error return is to the passed label) –Pass an exception handling subprogram to all subprograms

Copyright © 2015 Pearson. All rights reserved.1-6 Advantages of Built-in Exception Handling Error detection code is tedious to write and it clutters the program Exception handling encourages programmers to consider many different possible errors Exception propagation allows a high level of reuse of exception handling code

Copyright © 2015 Pearson. All rights reserved.1-7 Design Issues How and where are exception handlers specified and what is their scope? How is an exception occurrence bound to an exception handler? Can information about the exception be passed to the handler? Where does execution continue, if at all, after an exception handler completes its execution? (continuation vs. resumption) Is some form of finalization provided?

Copyright © 2015 Pearson. All rights reserved.1-8 Design Issues (continued) How are user-defined exceptions specified? Should there be default exception handlers for programs that do not provide their own? Can predefined exceptions be explicitly raised? Are hardware-detectable errors treated as exceptions that can be handled? Are there any predefined exceptions? How can exceptions be disabled, if at all?

Copyright © 2015 Pearson. All rights reserved.1-9 Exception Handling Control Flow

Copyright © 2015 Pearson. All rights reserved.1-10 Exception Handling in C++ Added to C++ in 1990 Design is based on that of CLU, Ada, and ML

Copyright © 2015 Pearson. All rights reserved.1-11 C++ Exception Handlers Exception Handlers Form: try { -- code that is expected to raise an exception } catch ( formal parameter ) { -- handler code }... catch ( formal parameter ) { -- handler code }

Copyright © 2015 Pearson. All rights reserved.1-12 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 © 2015 Pearson. All rights reserved.1-13 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 © 2015 Pearson. All rights reserved.1-14 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 handler is found, the default handler is called

Copyright © 2015 Pearson. All rights reserved.1-15 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 Other design choices –All exceptions are user-defined –Exceptions are neither specified nor declared –The default handler, unexpected, simply terminates the program; unexpected can be redefined by the user –Functions can list the exceptions they may raise –Without a specification, a function can raise any exception (the throw clause)

Copyright © 2015 Pearson. All rights reserved.1-16 Evaluation There are no predefined exceptions It is odd that exceptions are not named and that hardware- and system software- detectable exceptions cannot be handled Binding exceptions to handlers through the type of the parameter certainly does not promote readability

Copyright © 2015 Pearson. All rights reserved.1-17 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 © 2015 Pearson. All rights reserved.1-18 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 RuntimeException (e.g., ArrayIndexOutOfBoundsException and NullPointerException

Copyright © 2015 Pearson. All rights reserved.1-19 Java Exception Handlers Like those of C++, except every catch requires a named parameter and all parameters must be descendants of Throwable 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 MyException();

Copyright © 2015 Pearson. All rights reserved.1-20 Binding Exceptions to Handlers Binding an exception to a handler is simpler in Java than it is in C++ –An exception is bound to the first handler with a parameter is 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)

Copyright © 2015 Pearson. All rights reserved.1-21 Continuation If no handler is found in the try construct, the search is continued in the nearest enclosing try construct, etc. 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 To insure that all exceptions are caught, a handler can be included in any try construct that catches all exceptions –Simply use an Exception class parameter –Of course, it must be the last in the try construct

Copyright © 2015 Pearson. All rights reserved.1-22 Checked and Unchecked Exceptions The Java throws clause is quite different from the throw clause of C++ Exceptions of class Error and RunTimeException and all of their descendants are called unchecked exceptions; all other exceptions are called checked exceptions Checked exceptions that may be thrown by a method must be either: –Listed in the throws clause, or –Handled in the method

Copyright © 2015 Pearson. All rights reserved.1-23 Other Design Choices 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: –Catch and handle the exception –Catch the exception and throw an exception that is listed in its own throws clause –Declare it in its throws clause and do not handle it

Copyright © 2015 Pearson. All rights reserved.1-24 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

Copyright © 2015 Pearson. All rights reserved.1-25 Example A try construct with a finally clause can be used outside exception handling try { for (index = 0; index < 100; index++) { … if ( … ) { return; } //** end of if } //** end of try clause finally { … } //** end of try construct

Copyright © 2015 Pearson. All rights reserved.1-26 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 AssertionError exception is thrown Can be disabled during runtime without program modification or recompilation Two forms –assert condition ; –assert condition : expression ;

Copyright © 2015 Pearson. All rights reserved.1-27 Evaluation The types of exceptions makes more sense than in the case of C++ 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

Exception Handling in Python Exceptions are objects; the base class is BaseException All predefined and user-defined exceptions are derived from Exception Predefined subclasses of Exception are ArithmeticError (subclasses are OverflowError, ZeroDivisionError, and FloatingPointError ) and LookupError (subclasses are IndexError and KeyError ) Copyright © 2015 Pearson. All rights reserved.1-28

Exception Handling in Python (continued) try: - The try block except Exception1: - Handler for Exception1 except Exception2: - Handler for Exception2... else: - The else block (no exception is raised) finally: - the finally block (do it no matter what) Copyright © 2015 Pearson. All rights reserved.1-29

Exception Handling in Python (continued) Handlers handle the named exception plus all subclasses of that exception, so if the named exception is Exception, it handlers all predefined and user-defined exceptions Unhandled exceptions are propagated to the nearest enclosing try block; if no handler is found, the default handler is called Raise IndexError creates an instance The raised exception object can be gotten: except Exception as ex_obj: Copyright © 2015 Pearson. All rights reserved.1-30

Exception Handling in Python (continued) The assert statement tests its Boolean expression (first parameter) and sends its second parameter to the constructor for the exception object to be raised assert test, data Copyright © 2015 Pearson. All rights reserved.1-31

Exception Handling in Ruby Exceptions are objects There are many predefined exceptions All exceptions that are user handled are either StandardError class or a subclass of it StandardError is derived from Exception, which has two methods, message and backtrace Exceptions can be raised with raise, which often has the form: raise ″bad parameter″ if count == 0 Copyright © 2015 Pearson. All rights reserved.1-32

Exception Handling in Ruby (continued) Handlers are placed at the end of a begin- end block of code; introduced by rescue begin - Statements in the block rescue - Handler end The block could include else and/or ensure clauses, which are like else and finally in Java Copyright © 2015 Pearson. All rights reserved.1-33

Exception Handling in Ruby (continued) Unlike the other languages we have discussed, in Ruby the code that raised an exception can be rerun by placing a retry statement at the end of the handler Copyright © 2015 Pearson. All rights reserved.1-34

Copyright © 2015 Pearson. All rights reserved.1-35 Introduction to Event Handling An event is a notification that something specific has occurred, such as a mouse click on a graphical button The event handler is a segment of code that is executed in response to an event

Copyright © 2015 Pearson. All rights reserved.1-36 Java Swing GUI Components Text box is an object of class JTextField Radio button is an object of class JRadioButton Applet’s display is a frame, a multilayered structure Content pane is one layer, where applets put output GUI components can be placed in a frame Layout manager objects are used to control the placement of components

Copyright © 2015 Pearson. All rights reserved.1-37 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 An interface is used to make event- handling methods conform to a standard protocol A class that implements a listener must implement an interface for the listener

Copyright © 2015 Pearson. All rights reserved.1-38 The Java Event Model (continued) One class of events is ItemEvent, which is associated with the event of clicking a checkbox, a radio button, or a list item The ItemListener interface prescribes a method, itemStateChanged, which is a handler for ItemEvent events The listener is created with addItemListener

Event Handling in C# Event handling in C# (and the other.NET languages) is similar to that in Java.NET has two approaches, Windows Forms and Windows Presentation Foundation—we cover only the former (which is the original approach) An application subclasses the Form predefined class (defined in System.Windows.Forms ) There is no need to create a frame or panel in which to place the GUI components Label objects are used to place text in the window Radio buttons are objects of the RadioButton class Copyright © 2015 Pearson. All rights reserved.1-39

Event Handling in C# (continued) Components are positioned by assigning a new Point object to the Location property of the component private RadioButton plain = new RadioButton(); plain.Location = new Point(100, 300); plain.Text = ″Plain″; controls.Add(plain); All C# event handlers have the same protocol, the return type is void and the two parameters are of types object and EventArgs Copyright © 2015 Pearson. All rights reserved.1-40

Event Handling in C# (continued) An event handler can have any name A radio button is tested with the Boolean Checked property of the button private void rb_CheckedChanged (object o, EventArgs e) { if (plain.Checked) …... } To register an event, a new EventHandler object must be created and added to the predefined delegate for the event Copyright © 2015 Pearson. All rights reserved.1-41

Event Handling in C# (continued) When a radio button changes from unchecked to checked, the CheckedChanged event is raised The associated delegate is referenced by the name of the event If the handler was named rb_CheckedChanged, we could register it on the radio button named plain with: plain.CheckedChanged += new EventHandler (rb_CheckedChanged); Copyright © 2015 Pearson. All rights reserved.1-42

Copyright © 2015 Pearson. All rights reserved.1-43 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 Java event handling is defined on the Swing components C# event handling is the.NET model, which is similar to the Java model