Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 16: Exceptions and Templates Copyright © 2019 Pearson Education Ltd., All rights reserved. 16.1 Exceptions Copyright © 2019 Pearson Education Ltd., All rights reserved. ERROR HANDLING � What do you do when a function receives invalid input? int getValue(int index) { if(index < 0 || index >= size) { cout << “Invalid index” << endl; return -1; // return a dummy value } else return array[index]; } © Pearson Education Limited 2015 ERROR HANDLING � � � But wait…. Suppose the size of array was 10 Suppose returned value was used as an index of another array int result = otherArray[ getValue(12) ]; � � � � An error message will be printed (there is no element 12) Then, getValue() will return a -1. Invalid index! Conclusion: naïve error checking is not always enough, and not always safe © Pearson Education Limited 2015 ERROR HANDLING � What if: double divide(double num, double den) { if(den == 0) { cout << “Error: Division by zero\n”; return 0; // dummy value } else return num / den; } � � What if the dummy value is used in further calculations? Once again: naïve error checking is not always enough, and not always safe © Pearson Education Limited 2015 EXCEPTIONS: ELEGANT ERROR HANDLING � � � � Complex error conditions can be handled by Exceptions An exception is a value or an object that signals an error. In C++, a throw statement is used to signal that an exception or error has occurred “Throw” an exception: double divide(double num, double den) { if(den == 0) { throw “Error: Division by zero\n”; } else return num / den; } Instead of returning a meaningless dummy value, we will terminate the function immediately and indicate error © Pearson Education Limited 2015 EXCEPTIONS: ELEGANT ERROR HANDLING � What kind of exceptions can you throw? � throw -1; // throw a literal integer value � throw ENUM_INVALID_INDEX; // throw an enum value � throw “Division by zero"; // throw a char const * � throw dX; // throw a defined variable � throw MyException("Fatal Error 404"); // Throw an object of class MyException © Pearson Education Limited 2015 EXCEPTIONS: HANDLING AN EXCEPTION � To handle an exception program must have try/catch construct: general format � Statements that may throw exceptions. (functions) try { // throws an exception } catch(ExceptionParameter) { // code here handles the exception } © Pearson Education Limited 2015 EXCEPTIONS: ELEGANT ERROR HANDLING Statements that may throw exceptions. (functions) � double x=25,y=0,result; try { result = divide(x, y); // throws an exception } catch(char const * errMessage) { cout << errMessage; Code that handles } the exception © Pearson Education Limited 2015 EXCEPTIONS: ELEGANT ERROR HANDLING � You can throw more than one exception from the try block, and provide as many catch blocks as necessary: try { doSomething(); // throws an exception } catch(char const * errMessage) { cout << errMessage; // catch text exception } catch(int num) { cout << num; // catch int exception } catch(...) { // catch anything! } © Pearson Education Limited 2015 EXCEPTIONS - TERMINOLOGY � Exception: object or value that signals an error � Throw an exception: send a signal that an error has occurred � Catch/Handle an exception: process the exception; interpret the signal � If the exception was caught, the program carries on executing � What if you do not catch a thrown exception? Example � © Pearson Education Limited 2015 EXCEPTIONS – FLOW OF CONTROL 1. A function that throws an exception is called from within a try block 2. If the function throws an exception, the function terminates and the try block is immediately exited. A catch block to process the exception is searched for in the source code immediately following the try block. 3. If a catch block is found that matches the exception thrown, it is executed. If no catch block that matches the exception is found, the program terminates. © Pearson Education Limited 2015 FROM PROGRAM 16-1 © Pearson Education Limited 2015 FROM PROGRAM 16-1 © Pearson Education Limited 2015 What Happens in theTry/Catch Construct © Pearson Education Limited 2015 What if no exception is thrown? © Pearson Education Limited 2015 EXCEPTION-NOTES � The value that is thrown does not need to be used in catch block. in this case, no name is needed in catch parameter definition ⚫ catch block parameter definition does need the type of exception being caught catch ( int ) { ⚫ � } © Pearson Education Limited 2015 EXCEPTION NOT CAUGHT? � An exception will not be caught if: it is thrown from outside of a try{} block ⚫ there is no catch{} block that matches the data type of the thrown exception ⚫ � If an exception is not caught, the program will terminate double x = 25, y = 0, result; try { result = divide(x, y); // throws an exception } // terminate the program – no “catch”! © Pearson Education Limited 2015 EXCEPTIONS AND OBJECTS � � � Classes may require more detailed exceptions than just a single value or an error message An exception class can be defined within a class and thrown as an exception by a member function An exception class may have: ⚫ ⚫ � no members: used only to signal an error members: pass error data to the catch block A class can have more than one exception class class Rectangle { public: class NegativeWidth{}; //Exception classes class NegativeLength{};// …followed by the // rest of the class }; // see example code! © Pearson Education Limited 2015 WHAT HAPPENS AFTER CATCH BLOCK? � Once an exception is thrown, the program cannot return to throw point. The function executing the throw terminates (does not return) Other calling functions in try block terminate � This is known as unwinding the stack � If objects were created in the try block and an exception is thrown, they are destroyed. (Destructor is automatically executed) � � © Pearson Education Limited 2015 NESTED TRY/CATCH BLOCKS � try/catch blocks can occur within an enclosing try/catch block � Exceptions caught at an inner level can be passed up to a catch block at an outer level: catch ( int ) { ... throw; // pass exception up } // to next level � Known as “re-throwing exceptions” © Pearson Education Limited 2015 RE-THROWING EXCEPTIONS double function1(double x) { try { if(x < 0) throw -1; return sqrt(x); } catch ( int ) { cout << “negative value”; throw; // re-throw: let the function who } // called you handle it } double function2(double y) { try { double x = function1(y); return x; } catch(int) { /* handle it!… */ } } © Pearson Education Limited 2015