SlideShare a Scribd company logo
Exception Handling In worst case there must  be emergency exit Lecture slides by: Farhan Amjad
I normally forget the face, but in your case I’ll make an exception. Groucho Marx  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.   Franklin Delano Roosevelt  If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them. Jerome David Salinger
An  exception  is a condition that occurs at execution time and makes normal continuation of the program impossible When an exception occurs, the program must either terminate or jump to special code for handling the exception The special code for handling the exception is called an  exception handler Exceptions 16-
Exception Types: Used in situations when: Errors can potentially occur and the system can recover from them. Errors can be of different natures e.g.,  memory exhaustion division by zero arithmetic overflow out of bounds array subscript Errors will be dealt with in a different part of the program.
Exception handling  (II) 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 Useful when program cannot recover but must shut down cleanly
Exception Handling Not used in situations when: Errors are asynchronous in nature (e.g., network messages, disk I/O errors, mouse click errors). Interrupt processing are a better choice of techniques for these types of errors.
Exception Handling in C++ Tries  a block of code that may contain exceptions Throws  an exception when one is detected. Catches  the exception and handles it. Thus, there are three concepts: the  try  block the  throw ing of the exceptions the block that  catch es or handles the exception
The  try  Block A block which includes the code that may generate an error (an exception). try { .. ..  } Can be followed by one or more catch blocks which handle the exception
The  try  Block Control of the program passes from the statements in the  try  block, to the appropriate  catch  block. Functions called from the try block, directly or indirectly, could test for the presence of the error.
The  throw  Point Used to indicate that an exception has occurred. It is called “ throwing an exception ” Throw  normally specifies an operand: Will be caught by closest exception handler.
The  catch  Blocks Contain the exception handler. These know what to do with the exception - typically print out that a type of error has occurred. catch(  )  { . . .  }
Exception handler: Catch Block The three purposes of an exception handler: Recover from an exception to safely continue execution If full recovery is not possible, display or log error message(s) If the exception cannot be handled locally, clean up local resources and re-raise the exception to propagate it to another handler
Catching Exceptions catch  blocks are typically located right after the  try  block that could  throw  the exception. The exception will be “caught” by the closest exception handler that specifies the proper type.
Exception Handling Procedure When exception identified in the  try  block control passes from the  try  block to the closest  catch  block that meets the type criteria. The code in correct  catch  block is executed. Control passes beyond the last  catch  block if there are no exceptions. An exception not caught will cause program to terminate prematurely.
Exception Handling Procedure Exception Handlers searched in order for an appropriate match. If  more than 1 matches are appropriate, then the physically closest to the try block with threw the exception. The programmer determines the order of the catch blocks. Once an exception is thrown, control cannot return to the throw point.
Exception Syntax Class Aclass { Public: class AnError { }; Void Func(){ if(  /* error condition  */)   throw AnError(); }}; Int main() { Try { Aclass obj1;  Obj1.Func ();  //may cause error } Catch(Aclass::AnError) { //tell user about error; }  Return 0; }
Exception Handling - Example #include <iostream.h> class DivideByZeroError()   { public:  DivideByZeroError() : message(“Divide by Zero”) {}; void printMessage() const {cout  << message ;  } private: const char *message; This is called the  error class .
Exception Handling - Example float quotient(int num1, int num2) { if (num2 == 0) throw  DivideByZeroError(); return (float) num1/num2; } Throws an exception to the error class DivideByZeroError
Exception Handling - Example main() { cout << “Enter 2 integers”; int num1, num2. cin >> num1  >> num2; try  { float result = quotient(num1, num2); cout << “the quotient is” << result; }   . . . // continued on next slide
Exception Handling - Example catch (DivideByZeroError error)  { cout << “ERROR:” error.printMessage() cout << endl; return 1; } return 0; )
How it works! Catch block must be designed to catch an object of the exception class Exception class object can pass data to exception handler via data members An object of class  DivideByZeroError  is instantiated and named  error .
Example Discussion Note that the detection element,  quotient  is embedded indirectly into the  try  block. Note that the error message contained in the  exception class is printed out. The program control  skips  the catch block if an exception is not thrown. Several  catch  blocks can be placed in sequence after the  try  block.
Exception Syntax const int Max=3; Class stack{ private: int st[Max], top; Public: class Range { }; stack(){ top=-1;} Void push(int var) { If(top>=Max-1) throw Range(); return st[++top]=var; }}; 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; }
Nested try Blocks try{ ………… try{ --------- } catch( exceptionType ex) { ------------------- } } catch( eceptionType ex) { ------------------------ } 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
Computer encounters a  throw  statement in a  try  block The computer evaluates the  throw  expression, and immediately exits the  try  block 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 Flow of Control 16-
Exception Syntax const int Max=3; Class stack{ private: int st[Max], top; Public: class Full { }; class Empty{ }; stack(){ top=-1;} Void push(int var) { If(top>=Max-1) throw Full(); return st[++top]=var; } int pop() { if(top<0) throw Empty(); return st[top--]; } };
Exception Syntax int main() { Stack s1; try{  S1.push(11); s1.push(22);  S1.push(33); s1.push(44); Cout<<“1. pop…”<<s1.pop(); Cout<<“2. pop…”<<s1.pop(); Cout<<“3. pop…”<<s1.pop(); Cout<<“4. pop…”<<s1.pop(); } Catch(stack::Full) { Cout<<“Exception: Stack is Full”; }  return 0; } Catch(Stack::Empty) { Cout<<“Exception: Stack is Empty; } return  0; }
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.
Introduction to   C++ Templates and Exceptions C++ Function Templates C++ Class Templates
C++ Function Templates Approaches for functions that implement identical tasks for different data types Naïve Approach   Function Overloading Function Template Instantiating a Function Templates
Approach 1: Naïve Approach create unique functions with unique names for each combination of data types   difficult to keeping track of multiple function names   lead to programming errors
Example void PrintInt( int n ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << n << endl; } void PrintChar( char ch ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << ch << endl; } void PrintFloat( float x ) { … } void PrintDouble( double d ) { … } PrintInt (sum); PrintChar (initial); PrintFloat (angle);   To output the traced values, we insert:
Approach 2:Function Overloading (Review) The use of the same name for different C++ functions, distinguished from each other by their parameter lists Eliminates need to come up with many different names for identical tasks. Reduces the chance of unexpected results caused by using the wrong function name.
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:
Approach 3: Function Template A C++ language construct that allows the compiler to generate  multiple  versions of a function by allowing  parameterized data types . Template < TemplateParamList > FunctionDefinition FunctionTemplate TemplateParamDeclaration: placeholder   class  typeIdentifier  typename variableIdentifier
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
Instantiating a Function Template When the compiler instantiates a template, it substitutes the  template argument  for the  template parameter  throughout the function template. Function  <  TemplateArgList  > (FunctionArgList) TemplateFunction Call
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; } }
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
Class Template A C++ language construct that allows the compiler to generate  multiple  versions of a class by allowing  parameterized data types . Template < TemplateParamList > ClassDefinition Class Template TemplateParamDeclaration: placeholder     class  typeIdentifier    typename variableIdentifier
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
Instantiating a Class Template Class template arguments  must  be explicit. The compiler generates distinct class types called template classes or generated classes. When instantiating a template, a compiler substitutes the template argument for the template parameter throughout the class template.
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
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
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++; }
Another Template Example: passing two parameters template <class T, int size> class Stack {... T buf[size]; }; Stack<int,128> mystack; non-type parameter
Standard Template Library 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 Developed by Stepanov and Lee at HP labs in 1992 Become part of the C++ Standard in 1994
What’s in STL? Container classes: vector, list, deque, set, map, and etc… A large collection of algorithms, such as reverse, swap, heap, and etc.
Vector A sequence that supports random access to elements Elements can be inserted and removed at the beginning, the end and the middle Constant time random access Commonly used operations begin(), end(), size(), [], push_back(…), pop_back(), insert(…), empty()
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
Take Home Message 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 function templates class templates
Suggestion  Implement the distance class of Robert Lafore Book.

More Related Content

PPSX
Exception Handling
PPTX
Presentation on C++ Programming Language
PPT
Strings Functions in C Programming
PPTX
classes and objects in C++
PPTX
c++ programming Unit 2 basic structure of a c++ program
PPTX
Method overloading
PDF
Control statements
PPTX
interface in c#
Exception Handling
Presentation on C++ Programming Language
Strings Functions in C Programming
classes and objects in C++
c++ programming Unit 2 basic structure of a c++ program
Method overloading
Control statements
interface in c#

What's hot (20)

PPTX
Queue Implementation Using Array & Linked List
PPTX
PDF
Constructor and Destructor
PPTX
Strings in c++
PPTX
07. Virtual Functions
PPTX
Code smells and remedies
PPT
structure and union
PPT
Structure and union
PPTX
Control statements in c
PPTX
Templates in c++
PPTX
Intro to c++
PPTX
Control Flow Statements
PDF
Exception handling
PDF
Enumeration in Java Explained | Java Tutorial | Edureka
PPTX
Constructors in C++
PPTX
PDF
Files and streams
PPTX
C# File IO Operations
PPTX
Exception Handling in object oriented programming using C++
PPTX
Basic Data Types in C++
Queue Implementation Using Array & Linked List
Constructor and Destructor
Strings in c++
07. Virtual Functions
Code smells and remedies
structure and union
Structure and union
Control statements in c
Templates in c++
Intro to c++
Control Flow Statements
Exception handling
Enumeration in Java Explained | Java Tutorial | Edureka
Constructors in C++
Files and streams
C# File IO Operations
Exception Handling in object oriented programming using C++
Basic Data Types in C++
Ad

Viewers also liked (20)

PPTX
Exception handling
PPT
Exception handling in c++ by manoj vasava
PPTX
Exception Handling in C++
PDF
Exception Handling
PPT
Handling Exceptions In C &amp; C++[Part A]
PPTX
Exception handling in c
PPT
Unit iii
PPT
Handling Exceptions In C &amp; C++ [Part B] Ver 2
PPTX
Idiomatic C++
PPTX
The Style of C++ 11
PDF
Distributed Systems Design
PPT
STL ALGORITHMS
PPT
Operator overloading
PPTX
Improving The Quality of Existing Software
PDF
05 c++-strings
PPT
C++ Advanced
PPT
Exception handler
PPTX
Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11,...
PPTX
Web Service Basics and NWS Setup
PPTX
exception handling in cpp
Exception handling
Exception handling in c++ by manoj vasava
Exception Handling in C++
Exception Handling
Handling Exceptions In C &amp; C++[Part A]
Exception handling in c
Unit iii
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Idiomatic C++
The Style of C++ 11
Distributed Systems Design
STL ALGORITHMS
Operator overloading
Improving The Quality of Existing Software
05 c++-strings
C++ Advanced
Exception handler
Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11,...
Web Service Basics and NWS Setup
exception handling in cpp
Ad

Similar to Exception handling and templates (20)

PPT
F6dc1 session6 c++
PPTX
Exception handling
PPTX
Exception handling c++
PPT
UNIT III.ppt
PPT
UNIT III (2).ppt
PPT
Handling
PPTX
Lecture 1 Try Throw Catch.pptx
PPT
Exception handling
PPTX
Object Oriented Programming Using C++: C++ Exception Handling.pptx
PPTX
Lecture 09 Exception Handling(1 ) in c++.pptx
PDF
Exceptions and Exception Handling in C++
PPTX
Exceptions in C++ Object Oriented Programming.pptx
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PPTX
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
PPTX
6-Exception Handling and Templates.pptx
PPT
Lecture16
PPTX
Exception Handling in C++-Brief notes.pptx
PPTX
Exception handling chapter15
PDF
F6dc1 session6 c++
Exception handling
Exception handling c++
UNIT III.ppt
UNIT III (2).ppt
Handling
Lecture 1 Try Throw Catch.pptx
Exception handling
Object Oriented Programming Using C++: C++ Exception Handling.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
Exceptions and Exception Handling in C++
Exceptions in C++ Object Oriented Programming.pptx
22 scheme OOPs with C++ BCS306B_module5.pdf
Lecture 3.1.1 Try Throw Catch.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
6-Exception Handling and Templates.pptx
Lecture16
Exception Handling in C++-Brief notes.pptx
Exception handling chapter15

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
TR - Agricultural Crops Production NC III.pdf
PPH.pptx obstetrics and gynecology in nursing
human mycosis Human fungal infections are called human mycosis..pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
01-Introduction-to-Information-Management.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
VCE English Exam - Section C Student Revision Booklet
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
RMMM.pdf make it easy to upload and study
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Abdominal Access Techniques with Prof. Dr. R K Mishra
Module 4: Burden of Disease Tutorial Slides S2 2025
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
FourierSeries-QuestionsWithAnswers(Part-A).pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
TR - Agricultural Crops Production NC III.pdf

Exception handling and templates

  • 1. Exception Handling In worst case there must be emergency exit Lecture slides by: Farhan Amjad
  • 2. I normally forget the face, but in your case I’ll make an exception. Groucho Marx 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. Franklin Delano Roosevelt If they’re running and they don’t look where they’re going I have to come out from somewhere and catch them. Jerome David Salinger
  • 3. An exception is a condition that occurs at execution time and makes normal continuation of the program impossible When an exception occurs, the program must either terminate or jump to special code for handling the exception The special code for handling the exception is called an exception handler Exceptions 16-
  • 4. Exception Types: Used in situations when: Errors can potentially occur and the system can recover from them. Errors can be of different natures e.g., memory exhaustion division by zero arithmetic overflow out of bounds array subscript Errors will be dealt with in a different part of the program.
  • 5. Exception handling (II) 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 Useful when program cannot recover but must shut down cleanly
  • 6. Exception Handling Not used in situations when: Errors are asynchronous in nature (e.g., network messages, disk I/O errors, mouse click errors). Interrupt processing are a better choice of techniques for these types of errors.
  • 7. Exception Handling in C++ Tries a block of code that may contain exceptions Throws an exception when one is detected. Catches the exception and handles it. Thus, there are three concepts: the try block the throw ing of the exceptions the block that catch es or handles the exception
  • 8. The try Block A block which includes the code that may generate an error (an exception). try { .. .. } Can be followed by one or more catch blocks which handle the exception
  • 9. The try Block Control of the program passes from the statements in the try block, to the appropriate catch block. Functions called from the try block, directly or indirectly, could test for the presence of the error.
  • 10. The throw Point Used to indicate that an exception has occurred. It is called “ throwing an exception ” Throw normally specifies an operand: Will be caught by closest exception handler.
  • 11. The catch Blocks Contain the exception handler. These know what to do with the exception - typically print out that a type of error has occurred. catch( ) { . . . }
  • 12. Exception handler: Catch Block The three purposes of an exception handler: Recover from an exception to safely continue execution If full recovery is not possible, display or log error message(s) If the exception cannot be handled locally, clean up local resources and re-raise the exception to propagate it to another handler
  • 13. Catching Exceptions catch blocks are typically located right after the try block that could throw the exception. The exception will be “caught” by the closest exception handler that specifies the proper type.
  • 14. Exception Handling Procedure When exception identified in the try block control passes from the try block to the closest catch block that meets the type criteria. The code in correct catch block is executed. Control passes beyond the last catch block if there are no exceptions. An exception not caught will cause program to terminate prematurely.
  • 15. Exception Handling Procedure Exception Handlers searched in order for an appropriate match. If more than 1 matches are appropriate, then the physically closest to the try block with threw the exception. The programmer determines the order of the catch blocks. Once an exception is thrown, control cannot return to the throw point.
  • 16. Exception Syntax Class Aclass { Public: class AnError { }; Void Func(){ if( /* error condition */) throw AnError(); }}; Int main() { Try { Aclass obj1; Obj1.Func (); //may cause error } Catch(Aclass::AnError) { //tell user about error; } Return 0; }
  • 17. Exception Handling - Example #include <iostream.h> class DivideByZeroError() { public: DivideByZeroError() : message(“Divide by Zero”) {}; void printMessage() const {cout << message ; } private: const char *message; This is called the error class .
  • 18. Exception Handling - Example float quotient(int num1, int num2) { if (num2 == 0) throw DivideByZeroError(); return (float) num1/num2; } Throws an exception to the error class DivideByZeroError
  • 19. Exception Handling - Example main() { cout << “Enter 2 integers”; int num1, num2. cin >> num1 >> num2; try { float result = quotient(num1, num2); cout << “the quotient is” << result; } . . . // continued on next slide
  • 20. Exception Handling - Example catch (DivideByZeroError error) { cout << “ERROR:” error.printMessage() cout << endl; return 1; } return 0; )
  • 21. How it works! Catch block must be designed to catch an object of the exception class Exception class object can pass data to exception handler via data members An object of class DivideByZeroError is instantiated and named error .
  • 22. Example Discussion Note that the detection element, quotient is embedded indirectly into the try block. Note that the error message contained in the exception class is printed out. The program control skips the catch block if an exception is not thrown. Several catch blocks can be placed in sequence after the try block.
  • 23. Exception Syntax const int Max=3; Class stack{ private: int st[Max], top; Public: class Range { }; stack(){ top=-1;} Void push(int var) { If(top>=Max-1) throw Range(); return st[++top]=var; }}; 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. Nested try Blocks try{ ………… try{ --------- } catch( exceptionType ex) { ------------------- } } catch( eceptionType ex) { ------------------------ } 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. Computer encounters a throw statement in a try block The computer evaluates the throw expression, and immediately exits the try block 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 Flow of Control 16-
  • 26. Exception Syntax const int Max=3; Class stack{ private: int st[Max], top; Public: class Full { }; class Empty{ }; stack(){ top=-1;} Void push(int var) { If(top>=Max-1) throw Full(); return st[++top]=var; } int pop() { if(top<0) throw Empty(); return st[top--]; } };
  • 27. Exception Syntax int main() { Stack s1; try{ S1.push(11); s1.push(22); S1.push(33); s1.push(44); Cout<<“1. pop…”<<s1.pop(); Cout<<“2. pop…”<<s1.pop(); Cout<<“3. pop…”<<s1.pop(); Cout<<“4. pop…”<<s1.pop(); } Catch(stack::Full) { Cout<<“Exception: Stack is Full”; } return 0; } Catch(Stack::Empty) { Cout<<“Exception: Stack is Empty; } return 0; }
  • 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. Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates
  • 30. C++ Function Templates Approaches for functions that implement identical tasks for different data types Naïve Approach Function Overloading Function Template Instantiating a Function Templates
  • 31. Approach 1: Naïve Approach create unique functions with unique names for each combination of data types difficult to keeping track of multiple function names lead to programming errors
  • 32. Example void PrintInt( int n ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << n << endl; } void PrintChar( char ch ) { cout << &quot;***Debug&quot; << endl; cout << &quot;Value is &quot; << ch << endl; } void PrintFloat( float x ) { … } void PrintDouble( double d ) { … } PrintInt (sum); PrintChar (initial); PrintFloat (angle); To output the traced values, we insert:
  • 33. Approach 2:Function Overloading (Review) The use of the same name for different C++ functions, distinguished from each other by their parameter lists Eliminates need to come up with many different names for identical tasks. Reduces the chance of unexpected results caused by using the wrong function name.
  • 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. Approach 3: Function Template A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types . Template < TemplateParamList > FunctionDefinition FunctionTemplate TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
  • 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. Instantiating a Function Template When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template. Function < TemplateArgList > (FunctionArgList) TemplateFunction Call
  • 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. 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. Class Template A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types . Template < TemplateParamList > ClassDefinition Class Template TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier
  • 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. Instantiating a Class Template Class template arguments must be explicit. The compiler generates distinct class types called template classes or generated classes. When instantiating a template, a compiler substitutes the template argument for the template parameter throughout the class template.
  • 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. 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. 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. Another Template Example: passing two parameters template <class T, int size> class Stack {... T buf[size]; }; Stack<int,128> mystack; non-type parameter
  • 47. Standard Template Library 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 Developed by Stepanov and Lee at HP labs in 1992 Become part of the C++ Standard in 1994
  • 48. What’s in STL? Container classes: vector, list, deque, set, map, and etc… A large collection of algorithms, such as reverse, swap, heap, and etc.
  • 49. Vector A sequence that supports random access to elements Elements can be inserted and removed at the beginning, the end and the middle Constant time random access Commonly used operations begin(), end(), size(), [], push_back(…), pop_back(), insert(…), empty()
  • 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. Take Home Message 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 function templates class templates
  • 52. Suggestion Implement the distance class of Robert Lafore Book.

Editor's Notes

  • #36: 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 &lt;class T&gt; void sort(vector&lt;T&gt; &amp;); void f(vector&lt;int&gt;&amp; vi, vector&lt;string&gt;&amp; vs) { sort(vi); sort(vs); } template&lt;class T&gt; void sort(vector&lt;T&gt; &amp;v) { const size_t n = v.size(); for (int gap=n/2; 0 &lt; gap; gap /= 2) for (int I = gap; I &lt; n; i++) for (j = I – gap; 0 &lt;= j; j-=gap) if (v[j+gap]&lt;v[j]) { T temp = v[j]; v[j] = v[i]; v[j+gap] = temp; } }
  • #39: Shell sort
  • #42: Template &lt;class ItemType&gt; 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 &lt;class ItemType&gt;
  • #43: 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.
  • #44: The name of a class template followed by a type bracketed by &lt;&gt; is the name of a class (as defined by the template) and can be used exactly like other class names.
  • #47: 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
  • #48: 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.
  • #49: 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.