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

What's hot (20)

PPTX
Abstract Data Types
karthikeyanC40
 
PPTX
Pointers in c++
Vineeta Garg
 
PPTX
classes and objects in C++
HalaiHansaika
 
PDF
Function overloading ppt
Prof. Dr. K. Adisesha
 
PPT
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
PPTX
Abstraction java
MahinImran
 
PPTX
This pointer
Kamal Acharya
 
PPT
Java: GUI
Tareq Hasan
 
PPT
Class and object in C++
rprajat007
 
PPTX
Abstract class in c++
Sujan Mia
 
PPTX
Data Type Conversion in C++
Danial Mirza
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPTX
Java - Collections framework
Riccardo Cardin
 
PPT
Exception handling
Iblesoft
 
PPT
Object Oriented Design
Sudarsun Santhiappan
 
PPTX
I/O Streams
Ravi Chythanya
 
PPT
Python GUI Programming
RTS Tech
 
PPTX
Constructor in java
Pavith Gunasekara
 
Abstract Data Types
karthikeyanC40
 
Pointers in c++
Vineeta Garg
 
classes and objects in C++
HalaiHansaika
 
Function overloading ppt
Prof. Dr. K. Adisesha
 
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Abstraction java
MahinImran
 
This pointer
Kamal Acharya
 
Java: GUI
Tareq Hasan
 
Class and object in C++
rprajat007
 
Abstract class in c++
Sujan Mia
 
Data Type Conversion in C++
Danial Mirza
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Java - Collections framework
Riccardo Cardin
 
Exception handling
Iblesoft
 
Object Oriented Design
Sudarsun Santhiappan
 
I/O Streams
Ravi Chythanya
 
Python GUI Programming
RTS Tech
 
Constructor in java
Pavith Gunasekara
 

Viewers also liked (20)

PPTX
Exception handling
Abhishek Pachisia
 
PPT
Exception handling in c++ by manoj vasava
Manoj_vasava
 
PPTX
Exception Handling in C++
Deepak Tathe
 
PDF
Exception Handling
Alpesh Oza
 
PPT
Handling Exceptions In C &amp; C++[Part A]
ppd1961
 
PPTX
Exception handling in c
Memo Yekem
 
PPT
Unit iii
snehaarao19
 
PPT
Handling Exceptions In C &amp; C++ [Part B] Ver 2
ppd1961
 
PPTX
Idiomatic C++
Federico Ficarelli
 
PPTX
The Style of C++ 11
Sasha Goldshtein
 
PDF
Distributed Systems Design
Dennis van der Stelt
 
PPT
STL ALGORITHMS
fawzmasood
 
PPT
Operator overloading
farhan amjad
 
PPTX
Improving The Quality of Existing Software
Steven Smith
 
PDF
05 c++-strings
Kelly Swanson
 
PPT
C++ Advanced
Vivek Das
 
PPT
Exception handler
dishni
 
PPTX
Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11,...
Complement Verb
 
PPTX
Web Service Basics and NWS Setup
Northeastern University
 
PPTX
exception handling in cpp
gourav kottawar
 
Exception handling
Abhishek Pachisia
 
Exception handling in c++ by manoj vasava
Manoj_vasava
 
Exception Handling in C++
Deepak Tathe
 
Exception Handling
Alpesh Oza
 
Handling Exceptions In C &amp; C++[Part A]
ppd1961
 
Exception handling in c
Memo Yekem
 
Unit iii
snehaarao19
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
ppd1961
 
Idiomatic C++
Federico Ficarelli
 
The Style of C++ 11
Sasha Goldshtein
 
Distributed Systems Design
Dennis van der Stelt
 
STL ALGORITHMS
fawzmasood
 
Operator overloading
farhan amjad
 
Improving The Quality of Existing Software
Steven Smith
 
05 c++-strings
Kelly Swanson
 
C++ Advanced
Vivek Das
 
Exception handler
dishni
 
Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11,...
Complement Verb
 
Web Service Basics and NWS Setup
Northeastern University
 
exception handling in cpp
gourav kottawar
 
Ad

Similar to Exception handling and templates (20)

PDF
Exception handling
Pranali Chaudhari
 
PPTX
Exception handling
Waqas Abbasi
 
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
sindhus795217
 
PPTX
12. Exception Handling
Intro C# Book
 
PPT
Exceptions in C++exception handling in C++, computer programming.ppt
Manwa2500
 
PDF
Exception Handling notes in java exception
Ratnakar Mikkili
 
PDF
$Cash
ErandaMoney
 
PDF
$Cash
ErandaMoney
 
PDF
Java unit3
Abhishek Khune
 
PPT
Exception Handling
backdoor
 
PPT
Exception Handling Mechanism in .NET CLR
Kiran Munir
 
PPTX
Exception handling
priyaankasrivastavaa
 
PPTX
Exception handling
zindadili
 
PPTX
Interface andexceptions
saman Iftikhar
 
PPTX
Rethrowing exception- JAVA
Rajan Shah
 
PPTX
17 exceptions
dhrubo kayal
 
PPTX
Exception Handling in object oriented programming using C++
Janki Shah
 
PPTX
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
PPT
Md07 exceptions&assertion
Rakesh Madugula
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
Exception handling
Pranali Chaudhari
 
Exception handling
Waqas Abbasi
 
22 scheme OOPs with C++ BCS306B_module5.pdf
sindhus795217
 
12. Exception Handling
Intro C# Book
 
Exceptions in C++exception handling in C++, computer programming.ppt
Manwa2500
 
Exception Handling notes in java exception
Ratnakar Mikkili
 
Java unit3
Abhishek Khune
 
Exception Handling
backdoor
 
Exception Handling Mechanism in .NET CLR
Kiran Munir
 
Exception handling
priyaankasrivastavaa
 
Exception handling
zindadili
 
Interface andexceptions
saman Iftikhar
 
Rethrowing exception- JAVA
Rajan Shah
 
17 exceptions
dhrubo kayal
 
Exception Handling in object oriented programming using C++
Janki Shah
 
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Md07 exceptions&assertion
Rakesh Madugula
 
12. Java Exceptions and error handling
Intro C# Book
 
Ad

Recently uploaded (20)

PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Introduction to Indian Writing in English
Trushali Dodiya
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Introduction presentation of the patentbutler tool
MIPLM
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
infertility, types,causes, impact, and management
Ritu480198
 
Controller Request and Response in Odoo18
Celine George
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 

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.