Why exception handling in C++?

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 Introduction Try Throw Catch. Exception Handling Use exception handling to write programs that are –Clearer –More robust –More fault-tolerant.
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
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.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
 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.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CS Advanced C++ Exception Handling Topic #5.
 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 Programming Techniques Course Version 1.0.
Dale Roberts Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Object Oriented Programming
 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.
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.
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.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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 Outline 23.1 Introduction
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exception Handling How to handle the runtime errors.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 05: Object Oriented Programming:2014 Object-Oriented Programming in C++ Exception.
Namespace יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר 2016 יום ראשון 13 נובמבר.
Exception handling.
Exception Handling C++.
IS 0020 Program Design and Software Tools
Exceptions Error Handling and Recovery
16 Exception Handling.
Chapter 16 Exception Handling
Exceptions Exceptions are used to signal that an unexpected event has happened in a program C++ will generate exceptions for some errors in the program.
Exceptions.
EXCEPTION HANDLING IN C++
Andy Wang Object Oriented Programming in C++ COP 3330
Part IX Fundamentals of C and C++ Programming Exception Handling
EXCEPTION HANDLING.
Object Oriented Programming COP3330 / CGS5409
Chapter 14: Exception Handling
Exceptions with Functions
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 17 Templates and Exceptions Part 2
Advanced C++ Exception Handling
Exception Handling.
Exceptions 1 CMSC 202.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
Chapter 1 c++ structure C++ Input / Output
CMSC 202 Exceptions.
Exception Handling.
ENERGY 211 / CME 211 Lecture 24 November 14, 2008.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

Why exception handling in C++? Exception handling is better makes clear, robust, fault-tolerant programs C++ removes error handling code from "main line" of program Exception handling - catch errors before they occur deals with synchronous errors (i.e., divide by zero) does not deal with asynchronous errors - disk I/O completions, mouse clicks - use interrupt processing used when system can recover from error exception handler - recovery procedure typically used when error is dealt with in different place than where it occurred useful when program cannot recover but must shut down cleanly Exception handling should not be used for program control not optimized, can harm program performance Exception handling should be used for processing exceptional situations processing exceptions for components that cannot handle them directly processing exceptions for widely used components (libraries, classes, functions) that should not process their own exceptions large projects that require uniform error processing

Here’s an example of exception handling: vector <double> realvec(5); /* run through the vector and display each element, if possible */ for (int i =0; i<10; i++) { try { cout << "Element " << i << ": " << realvec.at(i) << endl; } catch (exception& e) { cout << "Element " << i << ": index exceeds vector dimensions." << endl; The method vector::at throws an out of range exception if the index is out of range. The other accessor vector::operator[] does not.

Let’s take a careful look: Exception Handling: try, throw, catch A function can throw an exception object if it detects an error object is typically a character string (error message) or class object if exception handler exists, exception caught and handled otherwise, program terminates Format enclose code that may have an error in try block follow with one or more catch blocks each catch block has an exception handler if exception occurs and matches parameter in catch block, code in catch block executed if no exception thrown, exception handlers skipped and control resumes after catch blocks throw point - place where exception occurred control cannot return to throw point

Example: Division by Zero (credit Deitel & Deitel) // An exception-handling example that checks for divide-by-zero exceptions. #include <iostream> #include <exception> using namespace std; // DivideByZeroException objects should be thrown by functions // upon detecting division-by-zero exceptions class DivideByZeroException : public exception { public: // constructor specifies default error message DivideByZeroException::DivideByZeroException() : exception( "attempted to divide by zero" ) {} }; // end class DivideByZeroException // a function that performs division and throws DivideByZeroException object if // divide-by-zero exception occurs double quotient( int numerator, int denominator ) { // throw DivideByZeroException if trying to divide by zero if ( denominator == 0 ) throw DivideByZeroException(); // terminate function // return division result return static_cast< double >( numerator ) / denominator; } // end function quotient The function quotient is defined to throw an exception object if denominator == 0

int main() { int number1; // user-specified numerator int number2; // user-specified denominator double result; // result of division cout << "Enter two integers (end-of-file to end): "; // enable user to enter two integers to divide while ( cin >> number1 >> number2 ) { try { result = quotient( number1, number2 ); cout << "The quotient is: " << result << endl; } // end try catch ( DivideByZeroException &divideByZeroException ) { cout << "Exception occurred: " << divideByZeroException.what() << endl; } // end catch cout << "\nEnter two integers (end-of-file to end): "; } // end while cout << endl; return 0; // terminate normally } // end main try block encloses code that may throw an exception, along with code that should not execute if an exception occurs. catch block follows try block, and contains exception-handling code.

Let’s look at this in a little more depth throw - indicates an exception has occurred usually has one operand (sometimes zero) of any type if operand an object, called an exception object conditional expression can be thrown code referenced in a try block can throw an exception exception caught by closest matching exception handler control exits current try block and goes to catch handler (if it exists) Example (inside function definition): if ( denominator == 0 ) throw DivideByZeroException(); throws a DivideByZeroException object Exception does not have to terminate the program it does, however, terminate the block where exception occurred

Catching an Exception Exception handlers are in catch blocks Format: catch( exceptionType parameterName){ exception handling code } caught if argument type matches throw type if not caught then terminate called which (by default) calls abort Example: catch ( DivideByZeroException ex) { cout << "Exception occurred: " << ex.what() <<'\n' catches exceptions of type DivideByZeroException To catch all exceptions catch(...) - catches all exceptions potentially thrown in a try block Weaknesses of this use: you do not know what type of exception occurred there is no parameter name - cannot reference the object

Catching an Exception (cont.) If no handler matches thrown object searches next enclosing try block if none found, terminate called if found, control resumes after last catch block if several handlers match thrown object, first one found is executed catch parameter matches thrown object when they are of the same type exact match required - no promotions/conversions allowed the catch parameter is a public base class of the thrown object the catch parameter is a base-class pointer/ reference type and the thrown object is a derived-class pointer/ reference type of that base the catch handler is catch( ... ) thrown const objects have const in the parameter type

Catching an Exception (cont.) Unreleased resources resources may have been allocated when exception thrown catch handler should delete space allocated by new and close any opened files catch handlers can throw exceptions exceptions can only be processed by outer try blocks When a catch handler finishes executing, any local variables defined in it (including the catch parameter) go out of scope; any succeeding catch handlers are ignored, and execution continues at the first line of code after the try/catch sequence If no exception occurs in a try block, the catch handlers are ignored.

Recap – exception handling so far: throw, try, and catch -- code that is expected to raise an exception along with code that should not be executed if the exception is raised } catch (formal parameter) { -- handler code ... try { result = quotient( number1, number2 ); cout << "The quotient is: " << result << endl; } // end try catch ( DivideByZeroException &divideByZeroException ) { cout << "Exception occurred: " << divideByZeroException.what() << endl; } // end catch

Some observations: catch is the name of all handlers--it is an overloaded name in C++ , so the formal parameter of each catch block must be unique The formal parameter does not need to 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

Exception Handling: One more Recap C++ has a built in error handling mechanism: exception handling Program statements you want to monitor are put into a try blocks If an exception occurs in the try block, an exception is thrown (using throw) The exception is caught using catch and processed The general form is as follows try { // try block } catch (type1 arg) { // catch block catch (type2 arg) {  The general form of the throw statement is as follows: throw ex; When an exception is thrown it is caught by the corresponding catch statement

Rules for throwing exceptions throw has to be executed: From within the try block itself From a function called from within the try block (either directly or indirectly) The value that is thrown is the value of the argument There may be multiple catch blocks associated with a given try block They have to immediately follow the try block If you throw an exception for which there is no matching catch block, the program may abort

Example: #include "stdafx.h" #include <iostream> #include <exception> using namespace System; using namespace std; int main(array<System::String ^> ^args) { cout << "Begin the example \n"; try { // beginning of the try block cout << "Inside the try block now \n"; throw 10; // throw an error cout << "This line should never print out \n"; } catch (int i) { // catch an error cout << "caught error number " << i << endl; cout << "Next statement after the catch block \n"; return 0; Once an exception has been thrown, control passes to the catch expression The try block is terminated After the catch executes control passes to the statement after the catch

An exception can be thrown from a statement outside the try block as long as it is in a function called from inside the try block // same includes as in first example today void foo (int test) { cout << "Inside foo, test is " << test << endl; if (test) throw test; } int main(array<System::String ^> ^args) cout << "Begin indirect throw \n \n"; try { // start of try block cout << "Inside the try block " << endl; foo (0); foo (1); foo (2); catch (int i) { // catch an error cout << "caught error number " << i << endl; cout << "Next statement after the catch block \n"; return 0; What happens here? foo(0) called print msg from inside foo test = 0 = false nothing thrown so return from foo foo (1) called test = 1 = true throw value of 1 catch the exception print from catch block exit catch block execute stmt after catch block

Using multiple catch statements void bar (int test) { try { if (test) throw test; else throw "Hi there!"; } catch (int i) { // catch an error cout << "caught error number " << i << endl; catch (char *str) {cout << "caught a string " << str << endl; int main(array<System::String ^> ^args) { cout << "Starting example 3 \n \n"; bar(1); bar(2); bar(0); bar(7); cout << "Last statement in main \n"; return 0; }

Catching all exceptions Sometimes you want a handler that will catch any old exception This is done using the ellipsis: catch (…) { // code to deal with exceptions } The example on the next slide illustrates use of this

Use of ellipsis catch blocks void baz (test) { try { if (test == 0) throw test; // int if (test == 1) throw 'x'; // char if (test == 2) throw 3.14159; } catch (int i) { // catch an int exception cout << "Caught the int " << i << endl; catch (...) cout << "caught something, don't know what \n"; int main(array<System::String ^> ^args) { cout << "Starting example 4 \n \n"; baz(0); baz(1); baz(2); cout << "Last statement in main \n"; return 0; }