Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Advertisements

Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
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.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 23 - Exception Handling Outline 23.1Introduction 23.2When Exception Handling Should Be Used 23.3Other.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
C++ Exception Handling
1 CSC241: Object Oriented Programming Lecture No 28.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 13 - Exception Handling Outline 13.1Introduction 13.2When Exception Handling Should Be Used.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
Exception Handling Outline 23.1 Introduction
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exception Handling How to handle the runtime errors.
EE4E. C++ Programming Lecture 6 Advanced Topics. Contents Introduction Introduction Exception handling in C++ Exception handling in C++  An object oriented.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
C ++ MULTIPLE CHOICE QUESTION
Exception Handling in C++
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
16 Exception Handling.
Chapter 16 Exception Handling: A Deeper Look
Chapter 16 Exception Handling
CS212: Object Oriented Analysis and Design
Chapter 14 – Exception Handling
Exception Handling: A Deeper Look
Andy Wang Object Oriented Programming in C++ COP 3330
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
EXCEPTION HANDLING.
Chapter 14: Exception Handling
Andy Wang Object Oriented Programming in C++ COP 3330
Exceptions 1 CMSC 202.
Object-Oriented Programming (OOP) Lecture No. 44
16 Exception Handling.
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts Introduction Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually works Exception Handling Resolve exceptions Program may be able to continue Controlled termination Write fault-tolerant programs As an example, we will handle a divide-by-zero error

Dale Roberts Exception-Handling Overview Consider pseudocode Perform a task If the preceding task did not execute correctly Perform error processing Perform next task If the preceding task did not execute correctly Perform error processing Mixing logic and error handling Can make program difficult to read/debug Exception handling removes error correction from "main line" of program

Dale Roberts Exception-Handling Overview Exception handling For synchronous errors (divide by zero, null pointer) Cannot handle asynchronous errors (independent of program) Disk I/O, mouse, keyboard, network messages Easy to handle errors Terminology Function that has error throws an exception Exception handler (if it exists) can deal with problem Catches and handles exception If no exception handler, uncaught exception Could terminate program

Dale Roberts Exception-Handling Overview C++ code try { code that may raise exception code that may raise exception} catch (exceptionType){ code to handle exception code to handle exception} try block encloses code that may raise exception One or more catch blocks follow Catch and handle exception, if appropriate Take parameter; if named, can access exception object

Dale Roberts Exception-Handling Overview

Dale Roberts 13.2 Exception-Handling Overview Throw point Location in try block where exception occurred If exception handled Program skips remainder of try block Resumes after catch blocks If not handled Function terminates Looks for enclosing catch block (stack unwinding, 13.8) If no exception Program skips catch blocks

Dale Roberts Other Error-Handling Techniques Ignore exception Typical for personal (not commercial) software Program may fail Abort program Usually appropriate Not appropriate for mission-critical software Set error indicators Unfortunately, may not test for these when necessary Test for error condition Call exit ( ) and pass error code

Dale Roberts Other Error-Handling Techniques setjump and longjump <csetjmp> Jump from deeply nested function to call error handler Can be dangerous Dedicated error handling new can have a special handler Discussed 13.11

Dale Roberts Simple Exception Handler -- Example #include #include main(){ main(){ //try Block //try Block try try {throw(long(1)); //catch(long) call} {throw(long(1)); //catch(long) call} //Handlers //Handlers catch (int x) catch (int x) {cout << "Catch Integer " << x << endl;} {cout << "Catch Integer " << x << endl;} catch (long x) catch (long x) {cout << "Catch Long " << x << endl;} {cout << "Catch Long " << x << endl;} catch (...) catch (...) {cout << "Catch Rest" << endl;} {cout << "Catch Rest" << endl;} } OUTPUT WILL BE: OUTPUT WILL BE: Catch Long 1 Catch Long 1 Earlier g++ compiler verions required the usae of the =fhandle-exceptions or – fexceptions flags. The current g++ compiler support exception handling by default.

Dale Roberts An Exception Handler Class -- Example #include<stream.h> #include //exit() class zero{ public: public: zero() //Constructor zero() //Constructor {cout<<"Class Zero Constructor Invoked!!"<<endl;} {cout<<"Class Zero Constructor Invoked!!"<<endl;}}; //Exception Checker Function void zero_check(int i){ if (i == 0) if (i == 0) throw zero(); //Argument is of zero class type.} throw zero(); //Argument is of zero class type.}main(){ //try block //try block try{for (int i = 2; ; i--){ try{for (int i = 2; ; i--){ zero_check(i); zero_check(i); cout << "Reciprocal: " << 1.0/i << endl;}} cout << "Reciprocal: " << 1.0/i << endl;}} //Handler //Handler catch(zero) catch(zero) {cout << "DIVIDE BY ZERO -- ERROR!!\n"; exit(-1);} {cout << "DIVIDE BY ZERO -- ERROR!!\n"; exit(-1);}} OUTPUT WILL BE: OUTPUT WILL BE: Reciprocal: 0.5 Reciprocal: 0.5 Reciprocal: 1 Reciprocal: 1 Class Zero Constructor Invoked!! Class Zero Constructor Invoked!! DIVIDE BY ZERO -- ERROR!! DIVIDE BY ZERO -- ERROR!!

Dale Roberts Simple Exception-Handling Example: Divide by Zero Keyword throw Throws an exception Use when error occurs Can throw almost anything (exception object, integer, etc.) throw myObject; throw 5; Exception objects Base class exception ( ) Constructor can take a string (to describe exception) Member function what() returns that string

Dale Roberts Simple Exception-Handling Example: Divide by Zero Upcoming example Handle divide-by-zero errors Define new exception class DivideByZeroException Inherit from exception In division function Test denominator If zero, throw exception ( throw object ) In try block Attempt to divide Have enclosing catch block Catch DivideByZeroException objects

Dale Roberts 1 // Fig. 13.1: fig13_01.cpp 2 // A simple exception-handling example that checks for 3 // divide-by-zero exceptions. 4 #include 5 6 using std::cout; 7 using std::cin; 8 using std::endl; 9 10 #include using std::exception; // DivideByZeroException objects should be thrown by functions 15 // upon detecting division-by-zero exceptions 16 class DivideByZeroException : public exception { public: // constructor specifies default error message 21 DivideByZeroException::DivideByZeroException() 22 : exception( "attempted to divide by zero" ) {} }; // end class DivideByZeroException 25

Dale Roberts 26 // perform division and throw DivideByZeroException object if 27 // divide-by-zero exception occurs 28 double quotient( int numerator, int denominator ) 29 { 30 // throw DivideByZeroException if trying to divide by zero 31 if ( denominator == 0 ) 32 throw DivideByZeroException(); // terminate function // return division result 35 return static_cast ( numerator ) / denominator; } // end function quotient int main() 40 { 41 int number1; // user-specified numerator 42 int number2; // user-specified denominator 43 double result; // result of division cout << "Enter two integers (end-of-file to end): "; 46

Dale Roberts 47 // enable user to enter two integers to divide 48 while ( cin >> number1 >> number2 ) { // try block contains code that might throw exception 51 // and code that should not execute if an exception occurs 52 try { 53 result = quotient( number1, number2 ); 54 cout << "The quotient is: " << result << endl; } // end try // exception handler handles a divide-by-zero exception 59 catch ( DivideByZeroException &divideByZeroException ) { 60 cout << "Exception occurred: " 61 << divideByZeroException.what() << endl; } // end catch cout << "\nEnter two integers (end-of-file to end): "; } // end while cout << endl; return 0; // terminate normally } // end main

Dale Roberts Enter two integers (end-of-file to end): The quotient is: Enter two integers (end-of-file to end): Exception occurred: attempted to divide by zero Enter two integers (end-of-file to end): ^Z

Dale Roberts Rethrowing an Exception Rethrowing exceptions Use when exception handler cannot process exception Can still rethrow if handler did some processing Can rethrow exception to another handler Goes to next enclosing try block Corresponding catch blocks try to handle To rethrow Use statement " throw;" No arguments Terminates function

Dale Roberts 1 // Fig. 13.2: fig13_02.cpp 2 // Demonstrating exception rethrowing. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::exception; // throw, catch and rethrow exception 13 void throwException() 14 { 15 // throw exception and catch it immediately 16 try { 17 cout << " Function throwException throws an exception\n"; 18 throw exception(); // generate exception } // end try // handle exception 23 catch ( exception &caughtException ) { 24 cout << " Exception handled in function throwException" 25 << "\n Function throwException rethrows exception"; throw; // rethrow exception for further processing } // end catch

Dale Roberts cout << "This also should not print\n"; } // end function throwException int main() 36 { 37 // throw exception 38 try { 39 cout << "\nmain invokes function throwException\n"; 40 throwException(); 41 cout << "This should not print\n"; } // end try // handle exception 46 catch ( exception &caughtException ) { 47 cout << "\n\nException handled in main\n"; } // end catch cout << "Program control continues after catch in main\n"; return 0; } // end main

Dale Roberts main invokes function throwException Function throwException throws an exception Exception handled in function throwException Function throwException rethrows exception Exception handled in main Program control continues after catch in main

Dale Roberts 13.6 Exception Specifications List of exceptions function can throw Also called throw list int someFunction( double value ) throw ( ExceptionA, ExceptionB, ExceptionC ) throw ( ExceptionA, ExceptionB, ExceptionC ) { // function body } Can only throw ExceptionA, ExceptionB, and ExceptionC (and derived classes) If throws other type, function unexpected called By default, terminates program (more 13.7) If no throw list, can throw any exception If empty throw list, cannot throw any exceptions

Dale Roberts Processing Unexpected Exceptions Function unexpected Calls function registered with set_unexpected <exception> Calls terminate by default set_terminate Sets what function terminate calls By default, calls abort If redefined, still calls abort after new function finishes Arguments for set functions Pass pointer to function Function must take no arguments Returns void

Dale Roberts Stack Unwinding If exception thrown but not caught Goes to enclosing try block Terminates current function Unwinds function call stack Looks for try / catch that can handle exception If none found, unwinds again If exception never caught Calls terminate

Dale Roberts 1 // Fig. 13.3: fig13_03.cpp 2 // Demonstrating stack unwinding. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::runtime_error; // function3 throws run-time error 13 void function3() throw ( runtime_error ) 14 { 15 throw runtime_error( "runtime_error in function3" ); // fourth 16 } // function2 invokes function3 19 void function2() throw ( runtime_error ) 20 { 21 function3(); // third 22 } 23

Dale Roberts 24 // function1 invokes function2 25 void function1() throw ( runtime_error ) 26 { 27 function2(); // second 28 } // demonstrate stack unwinding 31 int main() 32 { 33 // invoke function1 34 try { 35 function1(); // first } // end try // handle run-time error 40 catch ( runtime_error &error ) // fifth 41 { 42 cout << "Exception occurred: " << error.what() << endl; } // end catch return 0; } // end main Exception occurred: runtime_error in function3

Dale Roberts Constructors, Destructors and Exception Handling Error in constructor new fails; cannot allocate memory Cannot return a value - how to inform user? Hope user examines object, notices errors Set some global variable Good alternative: throw an exception Destructors automatically called for member objects Called for automatic variables in try block Can catch exceptions in destructor

Dale Roberts Exceptions and Inheritance Exception classes Can be derived from base classes I.e., exception If catch can handle base class, can handle derived classes Polymorphic programming

Dale Roberts Processing new Failures When new fails to get memory Should throw bad_alloc exception Defined in Defined in Some compilers have new return 0 Result depends on compiler

Dale Roberts Standard Library Exception Hierarchy Exception hierarchy Base class exception ( ) Virtual function what, overridden to provide error messages Sample derived classes runtime_error, logic_error bad_alloc, bad_cast, bad_typeid Thrown by new, dynamic_cast and typeid To catch all exceptions catch(...) catch( exception AnyException) Will not catch user-defined exceptions

Dale Roberts Acknowledgements These slides were originally development by Dr. Uday Murthy and Dr. Rajeev Raje. Some contents comes from the Deitel slides that accompany your text.