Ch 11. Exception Handling Timothy Budd Oregon State University.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
CS102--Object Oriented Programming
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Jerry Lebowitz. Topics  Provides a facility for a systematic object oriented approach to handling runtime errors ◦ Can also handle runtime errors.
C++ Exception Handling
1 CSC241: Object Oriented Programming Lecture No 28.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
Rossella Lau Lecture 9, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 9: Application with Exception Handling 
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
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
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Chapter 12: Exception Handling
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
Exceptions Handling Exceptionally Sticky Problems.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Friend classes Friend class methods Nested classes Throwing exceptions, try blocks and catch blocks Exception classes Runtime type identification (RTTI)
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions in the Java programming language J. W. Rider.
C ++ MULTIPLE CHOICE QUESTION
Java Exceptions a quick review….
Exception Handling in C++
CS212: Object Oriented Analysis and Design
Chapter 14: Exception Handling
Java Programming Language
CISC/CMPE320 - Prof. McLeod
Exception Handling.
Presentation transcript:

Ch 11. Exception Handling Timothy Budd Oregon State University

Ch 11. Exception Handling2 Introduction Exception handling is a relatively new addition to the C++ and still not widely used. Prior to the introduction of the feature, programmers dealt with unusual situations in a number of different ways. Need to know alternative techniques that have been used to address similar problems.

Ch 11. Exception Handling3 Flags and Return Codes When functions return an error flag, the result should always be checked. FILE * fp = fopen("myData", "r"); // open file for read if (fp == 0)... // handle error case else... // handle correctly opened case

Ch 11. Exception Handling4 The stream I/O system does not return an error status flag directly, but rather it yields a value that can be converted into a boolean value that indicates the error: istream fin("filename.dat"); // open file if (! fin) { // convert to boolean and test //... handle error case } FILE *fp = fopen("rahrah.dat", "w"); // open file fputc('O', fp); // write a few characters fputc('S', fp); fputc('U', fp); if (ferror(fp)) // did an error occur in any of the previous?... // handle error case

Ch 11. Exception Handling5 errono should always be checked after calling any function in which it might be set. # include // include errno definition... double x =...; errno = 0; // clear out error flag double d = sqrt(x); if (errno == EDOM) // test global status flag... // handle error case // is sqrt evaluated first, or g? double d = sqrt(x) * g(); // worse, what happens if g clears // a flag that was set by sqrt ? double g () { errno = 0; return * sin(42); }

Ch 11. Exception Handling6 The Assertion Library Assertion package: run-time diagnostic information A boolean expression that should never be false if the program is operating correctly. If the value evaluate to false, a diagnostic error message is printed and the program is halted by calling the STL function abort.

Ch 11. Exception Handling7 The Assertion Library # include // include assertion package... assert (size != 0); // check size before dividing double val = sum / size; // do calculation Never turn off assertion checking.

Ch 11. Exception Handling8 The setjmp and longjmp Facility Prior to the introduction of exception in C++ setjmp: errors often occur many levels deep, rather than unwinding the sequence of calls, better to simply jump back to an earlier point in execution to handle the error. Avoid the setjmp facility in new code, as exceptions provide the same functionality.

Ch 11. Exception Handling9 # include // include setjmp library... jmp_buf Processing_Failed; // create a jump buffer if (setjmp(Processing_Failed)) {... // handle error case } else {... doProcessing(); // handle program execution }

Ch 11. Exception Handling10 When encounter an unrecoverable error, programmer can invoke the longjmp, passing as an argument the jump buffer and a nonzero integer value, rather than tracking back through the sequence of function invocations : void doProcessing() { ObjectType anObject; // declare an object value.. // go through several layers of function call doMoreProcessing(); } void doMoreProcessing() {... if (somethingWrong) longjmp (Processing_Failed, 13); }

Ch 11. Exception Handling11 Activation Record Stack anObject Local data for functin main Local data for function doProcessing Local data for function doMoreProcessing Local data for function main

Ch 11. Exception Handling12 Signals User hitting a break key, a floating point exception, a loss of carrier on a phone line, segmentation violation, or a bus error are reported to the program by means of a signal. A signal handler is a procedure that takes as an argument a single integer value. This integer is used to encode the type of signal being processed: # include // include signal definitions void handler (int a) { // handle the signal //... // reset the signal handler signal (a, handler); }

Ch 11. Exception Handling13 Exception Types Exception in C++ need not be a subclass of Throwable. The value thrown in conjunction with an exception can be any type.

Ch 11. Exception Handling14 A class hierarchy in the header file stdexcept in STL exception logic_error length_error domain_error out_of_range invalid_argument runtime_error range_error overflow_error underflow_error bad_alloc bad_cast bad_exception bad_typeid

Ch 11. Exception Handling15 Catch-all exception handler in Java. // Java Catch-All Example try { //... } catch (Exception e) { // catch all exceptions //... }

Ch 11. Exception Handling16 C++ permits ellipses to be used as the catch argument. // C++ Catch-All example try { //... } catch (... ) { // catch all exceptions //... } try {... } catch (... ) { // catch all exceptions // perform clean up actions throw; // pass action on to higher level }

Ch 11. Exception Handling17 Rethrowing Exceptions In Java, a catch clause can rethrow an exception. try { // Java rethrow exception example //... } catch (exception e) { // perform some action throw e; // resend exception } C++ allows simply an unadorned throw statement, which is interpreted to throw the same value as the current catch clause.

Ch 11. Exception Handling18 No finally Clause The finally clause in Java permits a section of code to be executed regardless of whether an exception is thrown. No similar facility in C++ Alternative way: create a dummy class and variable whose sole purpose is to launch a destructor when the try block is executed. Clean-up code is performed before the catch clauses.

Ch 11. Exception Handling19 class CleanUp { ~CleanUp () { //... put common clean up code here } }; //... try { CleanUp dummy; //... } catch (IOError & e) { //... } catch (RunTimeError & e) { //... } //... continue with execution

Ch 11. Exception Handling20 Reference as Exceptions The binding of a thrown value to an exception handler is a form of assignment. To avoid the slicing problem, exception handlers should declare their variables by reference.

Ch 11. Exception Handling21 Exception Class Clonability In Java, the value thrown is generally a newly created heap-based object, formed using the new operator. In C++, the object is often a nameless temporary value, formed by simply naming the class and any arguments used by the constructor. Always write a copy constructor for any user-defined exception class.

Ch 11. Exception Handling22 class ParseException { public: // constructors ParseException (string & why) : reason(why) { } ParseException (ParseException & why) : reason(why.reason) { } // operators void operator = (ParseException & why) { reason = why.reason; } operator string () { return reason; } private: string reason; }... // throw an error, creates a temporary value throw ParseException("missing expression");

Ch 11. Exception Handling23 No Need to Document Exception In C++, a function need not declare the possibility of throwing an exception in the function header. int f () throw (range_error); // will only throw range error int g (); // can possibly throw anything To indicate a function throws no exceptions, an empty list must be specified: int h () throw (); // throws no exceptions Backward compatibility for legacy code.

Ch 11. Exception Handling24 Always document a potential exception by placing a throw list in the function header. class Parent { // do think the throw an exception public: virtual void test (int i) { printf("parent test"); } }; class Child extends Parent { public: virtual void test (int i) { throw "executed child test"; } };

Ch 11. Exception Handling25 Standard Exceptions Only a handful of exception can be generated by function in the STL, including the following: NameThrown by bad_allocThe operator new bad_castDynamic cast operator bad_typeidThe typeid function out_of_rangeBitset subscript, vector functin at invalid_argumentDitset constructor

Ch 11. Exception Handling26 void f () throw (string) { //... g(); } void g () { // why not throw an irrational value? throw ; }