Exception handling and templates


Published on

Published in: Education
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • For most people, the first and most obvious use of templates is to define and use container classes such as string, vector, list and map. Soon after, the need for template functions arises. Sorting an array is a simple example: template <class T> void sort(vector<T> &); void f(vector<int>& vi, vector<string>& vs) { sort(vi); sort(vs); } template<class T> void sort(vector<T> &v) { const size_t n = v.size(); for (int gap=n/2; 0 < gap; gap /= 2) for (int I = gap; I < n; i++) for (j = I – gap; 0 <= j; j-=gap) if (v[j+gap]<v[j]) { T temp = v[j]; v[j] = v[i]; v[j+gap] = temp; } }
  • Shell sort
  • Template <class ItemType> says that ItemType is a type name, it need not be the name of a class. The scope of ItemType extends to the end of the declaration prefixed by template <class ItemType>
  • The process of generating a class declaration from a template class and a template argument is often called template instantiation. Similarly, a function is generated (“instantiated”) from a template function plus a template argument. A version of a template for a particular template argument is called a specialization.
  • The name of a class template followed by a type bracketed by <> is the name of a class (as defined by the template) and can be used exactly like other class names.
  • A template can take type parameters, parameters of ordinary types such as ints, and template parameters. For example, simple and constrained containers such as Stack or Buffer can be important where run-time efficiency and compactness are paramount. Passing a size as a template argument allows Stack’s implementer to avoid free store use. An integer template argument must be constant
  • STL , is a C++ library of container classes, algorithms, and iterators; it provides many of the basic algorithms and data structures of computer science. The STL is a generic library, meaning that its components are heavily parameterized: almost every component in the STL is a template.
  • Like many class libraries, the STL includes container classes: classes whose purpose is to contain other objects. The STL includes the classes vector , list , deque , set , multiset , map , multimap , hash_set , hash_multiset , hash_map , and hash_multimap . A list is a doubly linked list. That is, it is a Sequence that supports both forward and backward traversal, and (amortized) constant time insertion and removal of elements at the beginning or the end. A deque is very much like a vector: like vector, it is a sequence that supports random access to elements, constant time insertion and removal of elements at the end of the sequence, and linear time insertion and removal of elements in the middle Set is a c ontainer that stores objects in a sorted manner. Map is also a set, the only difference is that in a map, each element must be assigned a key.
  • Exception handling and templates

    1. 1. Exception Handling In worst case there must be emergency exit Lecture slides by: Farhan Amjad
    2. 2. <ul><li>I normally forget the face, but in your case I’ll make an exception. </li></ul><ul><ul><li>Groucho Marx </li></ul></ul><ul><li>It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. </li></ul><ul><ul><li>Franklin Delano Roosevelt </li></ul></ul><ul><li>If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them. </li></ul><ul><ul><li>Jerome David Salinger </li></ul></ul>
    3. 3. <ul><li>An exception is a condition that occurs at execution time and makes normal continuation of the program impossible </li></ul><ul><li>When an exception occurs, the program must either terminate or jump to special code for handling the exception </li></ul><ul><li>The special code for handling the exception is called an exception handler </li></ul>Exceptions 16-
    4. 4. Exception Types: <ul><li>Used in situations when: </li></ul><ul><ul><li>Errors can potentially occur and the system can recover from them. </li></ul></ul><ul><ul><li>Errors can be of different natures e.g., </li></ul></ul><ul><ul><ul><ul><li>memory exhaustion </li></ul></ul></ul></ul><ul><ul><ul><ul><li>division by zero </li></ul></ul></ul></ul><ul><ul><ul><ul><li>arithmetic overflow </li></ul></ul></ul></ul><ul><ul><ul><ul><li>out of bounds array subscript </li></ul></ul></ul></ul><ul><ul><li>Errors will be dealt with in a different part of the program. </li></ul></ul>
    5. 5. Exception handling (II) <ul><li>Exception handling - catch errors before they occur </li></ul><ul><ul><li>Deals with synchronous errors (i.E., Divide by zero) </li></ul></ul><ul><ul><li>Does not deal with asynchronous errors - disk I/O completions, mouse clicks - use interrupt processing </li></ul></ul><ul><ul><li>Used when system can recover from error </li></ul></ul><ul><ul><ul><li>Exception handler - recovery procedure </li></ul></ul></ul><ul><ul><li>Useful when program cannot recover but must shut down cleanly </li></ul></ul>
    6. 6. Exception Handling <ul><li>Not used in situations when: </li></ul><ul><ul><li>Errors are asynchronous in nature (e.g., network messages, disk I/O errors, mouse click errors). </li></ul></ul><ul><ul><li>Interrupt processing are a better choice of techniques for these types of errors. </li></ul></ul>
    7. 7. Exception Handling in C++ <ul><li>Tries a block of code that may contain exceptions </li></ul><ul><li>Throws an exception when one is detected. </li></ul><ul><li>Catches the exception and handles it. </li></ul><ul><li>Thus, there are three concepts: </li></ul><ul><ul><ul><li>the try block </li></ul></ul></ul><ul><ul><ul><li>the throw ing of the exceptions </li></ul></ul></ul><ul><ul><ul><li>the block that catch es or handles the exception </li></ul></ul></ul>
    8. 8. The try Block <ul><li>A block which includes the code that may generate an error (an exception). </li></ul><ul><li>try { .. </li></ul><ul><li>.. } </li></ul><ul><li>Can be followed by one or more catch blocks which handle the exception </li></ul>
    9. 9. The try Block <ul><li>Control of the program passes from the statements in the try block, to the appropriate catch block. </li></ul><ul><li>Functions called from the try block, directly or indirectly, could test for the presence of the error. </li></ul>
    10. 10. The throw Point <ul><li>Used to indicate that an exception has occurred. </li></ul><ul><li>It is called “ throwing an exception ” </li></ul><ul><li>Throw normally specifies an operand: </li></ul><ul><li>Will be caught by closest exception handler. </li></ul>
    11. 11. The catch Blocks <ul><li>Contain the exception handler. </li></ul><ul><li>These know what to do with the exception - typically print out that a type of error has occurred. </li></ul><ul><li>catch( ) { </li></ul><ul><li>. . . </li></ul><ul><li>} </li></ul>
    12. 12. Exception handler: Catch Block <ul><li>The three purposes of an exception handler: </li></ul><ul><ul><li>Recover from an exception to safely continue execution </li></ul></ul><ul><ul><li>If full recovery is not possible, display or log error message(s) </li></ul></ul><ul><ul><li>If the exception cannot be handled locally, clean up local resources and re-raise the exception to propagate it to another handler </li></ul></ul>
    13. 13. Catching Exceptions <ul><li>catch blocks are typically located right after the try block that could throw the exception. </li></ul><ul><li>The exception will be “caught” by the closest exception handler that specifies the proper type. </li></ul>
    14. 14. Exception Handling Procedure <ul><li>When exception identified in the try block </li></ul><ul><ul><li>control passes from the try block to the closest catch block that meets the type criteria. </li></ul></ul><ul><ul><li>The code in correct catch block is executed. </li></ul></ul><ul><ul><li>Control passes beyond the last catch block if there are no exceptions. </li></ul></ul><ul><li>An exception not caught will cause program to terminate prematurely. </li></ul>
    15. 15. Exception Handling Procedure <ul><li>Exception Handlers searched in order for an appropriate match. </li></ul><ul><li>If more than 1 matches are appropriate, then the physically closest to the try block with threw the exception. </li></ul><ul><li>The programmer determines the order of the catch blocks. </li></ul><ul><li>Once an exception is thrown, control cannot return to the throw point. </li></ul>
    16. 16. Exception Syntax <ul><li>Class Aclass </li></ul><ul><li>{ </li></ul><ul><li>Public: </li></ul><ul><li>class AnError { }; </li></ul><ul><li>Void Func(){ </li></ul><ul><li>if( /* error condition */) </li></ul><ul><li> throw AnError(); </li></ul><ul><li>}}; </li></ul>Int main() { Try { Aclass obj1; Obj1.Func (); //may cause error } Catch(Aclass::AnError) { //tell user about error; } Return 0; }
    17. 17. Exception Handling - Example <ul><li>#include <iostream.h> </li></ul><ul><li>class DivideByZeroError() { </li></ul><ul><li>public: </li></ul><ul><li>DivideByZeroError() : </li></ul><ul><li>message(“Divide by Zero”) {}; </li></ul><ul><li>void printMessage() const {cout << message ; } </li></ul><ul><li>private: </li></ul><ul><li>const char *message; </li></ul><ul><li>This is called the error class . </li></ul>
    18. 18. Exception Handling - Example <ul><li>float quotient(int num1, int num2) </li></ul><ul><li>{ </li></ul><ul><li>if (num2 == 0) </li></ul><ul><li>throw DivideByZeroError(); </li></ul><ul><li>return (float) num1/num2; </li></ul><ul><li>} </li></ul><ul><li>Throws an exception to the error class DivideByZeroError </li></ul>
    19. 19. Exception Handling - Example <ul><li>main() </li></ul><ul><li>{ </li></ul><ul><li>cout << “Enter 2 integers”; </li></ul><ul><li>int num1, num2. </li></ul><ul><li>cin >> num1 >> num2; </li></ul><ul><li>try { </li></ul><ul><li>float result = quotient(num1, num2); </li></ul><ul><li>cout << “the quotient is” << result; </li></ul><ul><li>} </li></ul><ul><li> . . . </li></ul><ul><li>// continued on next slide </li></ul>
    20. 20. Exception Handling - Example <ul><li>catch (DivideByZeroError error) { </li></ul><ul><li>cout << “ERROR:” </li></ul><ul><li>error.printMessage() </li></ul><ul><li>cout << endl; </li></ul><ul><li>return 1; </li></ul><ul><li>} </li></ul><ul><li>return 0; </li></ul><ul><li>) </li></ul>
    21. 21. How it works! <ul><li>Catch block must be designed to catch an object of the exception class </li></ul><ul><li>Exception class object can pass data to exception handler via data members </li></ul><ul><li>An object of class DivideByZeroError is instantiated and named error . </li></ul>
    22. 22. Example Discussion <ul><li>Note that the detection element, quotient is embedded indirectly into the try block. </li></ul><ul><li>Note that the error message contained in the exception class is printed out. </li></ul><ul><li>The program control skips the catch block if an exception is not thrown. </li></ul><ul><li>Several catch blocks can be placed in sequence after the try block. </li></ul>
    23. 23. Exception Syntax <ul><li>const int Max=3; </li></ul><ul><li>Class stack{ </li></ul><ul><li>private: </li></ul><ul><li>int st[Max], top; </li></ul><ul><li>Public: </li></ul><ul><li>class Range { }; </li></ul><ul><li>stack(){ top=-1;} </li></ul><ul><li>Void push(int var) </li></ul><ul><li>{ </li></ul><ul><li>If(top>=Max-1) </li></ul><ul><li>throw Range(); </li></ul><ul><li>return st[++top]=var; </li></ul><ul><li>}}; </li></ul>int main() { Stack s1; try{ S1.push(11); s1.push(22); S1.push(33); s1.push(44); } Catch(stack::Range) { Cout<<“Exception: Stack is Full”; } return 0; }
    24. 24. Nested try Blocks <ul><li>try{ </li></ul><ul><li>………… </li></ul><ul><li>try{ </li></ul><ul><li>--------- </li></ul><ul><li>} </li></ul><ul><li>catch( exceptionType ex) </li></ul><ul><li>{ </li></ul><ul><li>------------------- </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>catch( eceptionType ex) </li></ul><ul><li>{ </li></ul><ul><li>------------------------ </li></ul><ul><li>} </li></ul>This handler catches the exception in the inner try block This handler catches the exception thrown anywhere in the outer try block as well as uncaught exceptions from the inner try block
    25. 25. <ul><li>Computer encounters a throw statement in a try block </li></ul><ul><li>The computer evaluates the throw expression, and immediately exits the try block </li></ul><ul><li>The computer selects an attached catch block that matches the type of the thrown value, places the value in the catch block’s formal parameter, and executes the catch block </li></ul>Flow of Control 16-
    26. 26. Exception Syntax <ul><li>const int Max=3; </li></ul><ul><li>Class stack{ </li></ul><ul><li>private: </li></ul><ul><li>int st[Max], top; </li></ul><ul><li>Public: </li></ul><ul><li>class Full { }; </li></ul><ul><li>class Empty{ }; </li></ul><ul><li>stack(){ top=-1;} </li></ul><ul><li>Void push(int var) </li></ul><ul><li>{ </li></ul><ul><li>If(top>=Max-1) </li></ul><ul><li>throw Full(); </li></ul><ul><li>return st[++top]=var; </li></ul><ul><li>} </li></ul>int pop() { if(top<0) throw Empty(); return st[top--]; } };
    27. 27. Exception Syntax <ul><li>int main() </li></ul><ul><li>{ </li></ul><ul><li>Stack s1; </li></ul><ul><li>try{ </li></ul><ul><li>S1.push(11); s1.push(22); </li></ul><ul><li>S1.push(33); s1.push(44); </li></ul><ul><li>Cout<<“1. pop…”<<s1.pop(); </li></ul><ul><li>Cout<<“2. pop…”<<s1.pop(); </li></ul><ul><li>Cout<<“3. pop…”<<s1.pop(); </li></ul><ul><li>Cout<<“4. pop…”<<s1.pop(); </li></ul><ul><li>} </li></ul><ul><li>Catch(stack::Full) </li></ul><ul><li>{ </li></ul><ul><li>Cout<<“Exception: Stack is Full”; </li></ul><ul><li>} return 0; } </li></ul>Catch(Stack::Empty) { Cout<<“Exception: Stack is Empty; } return 0; }
    28. 28. Exception Exercise: size = 4 Implement the class Box where you store the BALLS thrown by your college. Your program throws the exception BoxFullException( ) when size reaches to 4.
    29. 29. Introduction to C++ Templates and Exceptions <ul><li>C++ Function Templates </li></ul><ul><li>C++ Class Templates </li></ul>
    30. 30. C++ Function Templates <ul><li>Approaches for functions that implement identical tasks for different data types </li></ul><ul><ul><li>Naïve Approach </li></ul></ul><ul><ul><li>Function Overloading </li></ul></ul><ul><ul><li>Function Template </li></ul></ul><ul><li>Instantiating a Function Templates </li></ul>
    31. 31. Approach 1: Naïve Approach <ul><li>create unique functions with unique names for each combination of data types </li></ul><ul><ul><li>difficult to keeping track of multiple function names </li></ul></ul><ul><ul><li>lead to programming errors </li></ul></ul>
    32. 32. Example <ul><li>void PrintInt( int n ) </li></ul><ul><li>{ </li></ul><ul><li>cout << &quot;***Debug&quot; << endl; </li></ul><ul><li>cout << &quot;Value is &quot; << n << endl; </li></ul><ul><li>} </li></ul><ul><li>void PrintChar( char ch ) </li></ul><ul><li>{ </li></ul><ul><li>cout << &quot;***Debug&quot; << endl; </li></ul><ul><li>cout << &quot;Value is &quot; << ch << endl; </li></ul><ul><li>} </li></ul><ul><li>void PrintFloat( float x ) </li></ul><ul><li>{ </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>void PrintDouble( double d ) </li></ul><ul><li>{ </li></ul><ul><li>… </li></ul><ul><li>} </li></ul>PrintInt (sum); PrintChar (initial); PrintFloat (angle); To output the traced values, we insert:
    33. 33. Approach 2:Function Overloading (Review) <ul><ul><li>The use of the same name for different C++ functions, distinguished from each other by their parameter lists </li></ul></ul><ul><ul><li>Eliminates need to come up with many different names for identical tasks. </li></ul></ul><ul><ul><li>Reduces the chance of unexpected results caused by using the wrong function name. </li></ul></ul>
    34. 34. Example of Function Overloading void Print ( int n ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << n << endl; } void Print ( char ch ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << ch << endl; } void Print ( float x ) { } Print (someInt); Print (someChar); Print (someFloat); To output the traced values, we insert:
    35. 35. Approach 3: Function Template <ul><li>A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types . </li></ul>Template < TemplateParamList > FunctionDefinition FunctionTemplate TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
    36. 36. Example of a Function Template   template<class SomeType> void Print( SomeType val ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << val << endl; } Print<int>(sum); Print<char>(initial); Print<float>(angle); To output the traced values, we insert: Template parameter (class, user defined type, built-in types) Template argument
    37. 37. Instantiating a Function Template <ul><li>When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template. </li></ul>Function < TemplateArgList > (FunctionArgList) TemplateFunction Call
    38. 38. A more complex example   template<class T> void sort(vector<T>& v) { const size_t n = v.size(); for (int gap=n/2; 0<gap; gap/=2) for (int i=gap; i<n; i++) for (int j=i-gap; 0<j; j-=gap) if (v[j+gap]<v[j]) { T temp = v[j]; v[j] = v[j+gap]; v[j+gap] = temp; } }
    39. 39. Summary of Three Approaches Naïve Approach Different Function Definitions Different Function Names Function Overloading Different Function Definitions Same Function Name Template Functions One Function Definition (a function template) Compiler Generates Individual Functions
    40. 40. Class Template <ul><li>A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types . </li></ul>Template < TemplateParamList > ClassDefinition Class Template TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
    41. 41. Example of a Class Template template<class ItemType> class GList { public: bool IsEmpty() const; bool IsFull() const; int Length() const; void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; void SelSort(); void Print() const; GList(); // Constructor private: int length; ItemType data[MAX_LENGTH]; }; Template parameter
    42. 42. Instantiating a Class Template <ul><li>Class template arguments must be explicit. </li></ul><ul><li>The compiler generates distinct class types called template classes or generated classes. </li></ul><ul><li>When instantiating a template, a compiler substitutes the template argument for the template parameter throughout the class template. </li></ul>
    43. 43. Instantiating a Class Template // Client code   GList<int> list1; GList<float> list2; GList<string> list3;   list1.Insert(356); list2.Insert(84.375); list3.Insert(&quot;Muffler bolt&quot;); To create lists of different data types GList_int list1; GList_float list2; GList_string list3; template argument Compiler generates 3 distinct class types
    44. 44. Substitution Example class GList_int { public: void Insert( /* in */ ItemType item ); void Delete( /* in */ ItemType item ); bool IsPresent( /* in */ ItemType item ) const; private: int length; ItemType data[MAX_LENGTH]; }; int int int int
    45. 45. Function Definitions for Members of a Template Class template<class ItemType> void GList< ItemType >::Insert( /* in */ ItemType item ) { data[length] = item; length++; } //after substitution of float void GList< float >::Insert( /* in */ float item ) { data[length] = item; length++; }
    46. 46. Another Template Example: passing two parameters <ul><li>template <class T, int size> </li></ul><ul><li>class Stack {... </li></ul><ul><li>T buf[size]; </li></ul><ul><li>}; </li></ul><ul><li>Stack<int,128> mystack; </li></ul>non-type parameter
    47. 47. Standard Template Library <ul><li>In the late 70s Alexander Stepanov first observed that some algorithms do not depend on some particular implementation of a data structure but only on a few fundamental semantic properties of the structure </li></ul><ul><li>Developed by Stepanov and Lee at HP labs in 1992 </li></ul><ul><li>Become part of the C++ Standard in 1994 </li></ul>
    48. 48. What’s in STL? <ul><li>Container classes: vector, list, deque, set, map, and etc… </li></ul><ul><li>A large collection of algorithms, such as reverse, swap, heap, and etc. </li></ul>
    49. 49. Vector <ul><li>A sequence that supports random access to elements </li></ul><ul><ul><li>Elements can be inserted and removed at the beginning, the end and the middle </li></ul></ul><ul><ul><li>Constant time random access </li></ul></ul><ul><ul><li>Commonly used operations </li></ul></ul><ul><ul><ul><li>begin(), end(), size(), [], push_back(…), pop_back(), insert(…), empty() </li></ul></ul></ul>
    50. 50. Example of vectors // Instantiate a vector vector<int> V; // Insert elements V.push_back(2); // v[0] == 2 V.insert(V.begin(), 3); // V[0] == 3, V[1] == 2 // Random access V[0] = 5; // V[0] == 5 // Test the size int size = V.size(); // size == 2
    51. 51. Take Home Message <ul><li>Templates are mechanisms for generating functions and classes on type parameters . We can design a single class or function that operates on data of many types </li></ul><ul><ul><ul><li>function templates </li></ul></ul></ul><ul><ul><ul><li>class templates </li></ul></ul></ul>
    52. 52. Suggestion <ul><li>Implement the distance class of Robert </li></ul><ul><li>Lafore Book. </li></ul>