SlideShare a Scribd company logo
1 of 28
Introduction to
C++ Templates and Exceptions
C++ Function Templates
C++ Class Templates
Exception and Exception Handler
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 << "***Debug" << endl;
cout << "Value is " << n << endl;
}
void PrintChar( char ch )
{
cout << "***Debug" << endl;
cout << "Value is " << 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 << "***Debug" << endl;
cout << "Value is " << n << endl;
}
void Print( char ch )
{
cout << "***Debug" << endl;
cout << "Value is " << 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 << "***Debug" << endl;
cout << "Value is " << 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
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("Muffler bolt");
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 {...
};
Stack<int,128> mystack;
non-type parameter
Exception
• An exception is a unusual, often
unpredictable event, detectable by
software or hardware, that requires
special processing occurring at runtime
• In C++, a variable or class object that
represents an exceptional event.
Handling Exception
• If without handling,
• Program crashes
• Falls into unknown state
• An exception handler is a section of program
code that is designed to execute when a
particular exception occurs
• Resolve the exception
• Lead to known state, such as exiting the
program
Standard Exceptions
Exceptions Thrown by the Language
– new
Exceptions Thrown by Standard
Library Routines
Exceptions Thrown by user code,
using throw statement
The throw Statement
Throw: to signal the fact that an
exception has occurred; also called
raise
ThrowStatement throw Expression
The try-catch Statement
try
Block
catch (FormalParameter)
Block
catch (FormalParameter)
TryCatchStatement
How one part of the program catches and processes
the exception that another part of the program throws.
FormalParameter
DataType VariableName
…
Example of a try-catch Statement
try
{
// Statements that process personnel data and may throw
// exceptions of type int, string, and SalaryError
}
catch ( int )
{
// Statements to handle an int exception
}
catch ( string s )
{
cout << s << endl; // Prints "Invalid customer age"
// More statements to handle an age error
}
catch ( SalaryError )
{
// Statements to handle a salary error
}
Execution of try-catch
No
statements throw
an exception
Statement
following entire try-catch
statement
A
statement throws
an exception
Exception
Handler
Statements to deal with exception are executed
Control moves
directly to exception
handler
Throwing an Exception to be
Caught by the Calling Code
void Func4()
{
if ( error )
throw ErrType();
}
Normal
return
void Func3()
{
try
{
Func4();
}
catch ( ErrType )
{
}
}
Function
call
Return from
thrown
exception
Practice: Dividing by ZERO
Apply what you know:
int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom != 0)
return numer / denom;
else
//What to do?? do sth. to avoid program
//crash
}
int Quotient(int numer, // The numerator
int denom ) // The denominator
{
if (denom == 0)
throw DivByZero();
//throw exception of class DivByZero
return numer / denom;
}
A Solution
A Solution
// quotient.cpp -- Quotient program
#include<iostream.h>
#include <string.h>
int Quotient( int, int );
class DivByZero {}; // Exception class
int main()
{
int numer; // Numerator
int denom; // Denominator
//read in numerator
and denominator
while(cin)
{
try
{
cout << "Their quotient: "
<< Quotient(numer,denom) <<endl;
}
catch ( DivByZero )//exception handler
{
cout<<“Denominator can't be 0"<< endl;
}
// read in numerator and denominator
}
return 0;
}

More Related Content

What's hot

What's hot (20)

Java generics
Java genericsJava generics
Java generics
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Introduction to Java Programming Part 2
Introduction to Java Programming Part 2Introduction to Java Programming Part 2
Introduction to Java Programming Part 2
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Templates
TemplatesTemplates
Templates
 
Operators in java
Operators in javaOperators in java
Operators in java
 
C formatted and unformatted input and output constructs
C  formatted and unformatted input and output constructsC  formatted and unformatted input and output constructs
C formatted and unformatted input and output constructs
 
Modern C++
Modern C++Modern C++
Modern C++
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Java programs
Java programsJava programs
Java programs
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Scala functions
Scala functionsScala functions
Scala functions
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
02basics
02basics02basics
02basics
 

Viewers also liked

Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaManoj_vasava
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++Laxman Puri
 
Cisco Industry template - 4x3 dark
Cisco Industry template - 4x3 darkCisco Industry template - 4x3 dark
Cisco Industry template - 4x3 darkKVEDesign
 
Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
Programming in c++
Programming in c++Programming in c++
Programming in c++Baljit Saini
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryKumar Gaurav
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Analog Electronics ppt on Transition & diffusion capacitance by Being topper
Analog Electronics  ppt on Transition & diffusion capacitance by Being topperAnalog Electronics  ppt on Transition & diffusion capacitance by Being topper
Analog Electronics ppt on Transition & diffusion capacitance by Being topperVipin Kumar
 
Managing console input and output
Managing console input and outputManaging console input and output
Managing console input and outputgourav kottawar
 
C++ Advanced Features (TCF 2014)
C++ Advanced Features (TCF 2014)C++ Advanced Features (TCF 2014)
C++ Advanced Features (TCF 2014)Michael Redlich
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Paumil Patel
 

Viewers also liked (20)

Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
functions of C++
functions of C++functions of C++
functions of C++
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Cisco Industry template - 4x3 dark
Cisco Industry template - 4x3 darkCisco Industry template - 4x3 dark
Cisco Industry template - 4x3 dark
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Programming in c++
Programming in c++Programming in c++
Programming in c++
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Analog Electronics ppt on Transition & diffusion capacitance by Being topper
Analog Electronics  ppt on Transition & diffusion capacitance by Being topperAnalog Electronics  ppt on Transition & diffusion capacitance by Being topper
Analog Electronics ppt on Transition & diffusion capacitance by Being topper
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Managing console input and output
Managing console input and outputManaging console input and output
Managing console input and output
 
C++ Advanced Features (TCF 2014)
C++ Advanced Features (TCF 2014)C++ Advanced Features (TCF 2014)
C++ Advanced Features (TCF 2014)
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Lexical analysis
Lexical analysisLexical analysis
Lexical analysis
 

Similar to Templates exception handling

Similar to Templates exception handling (20)

TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Bw14
Bw14Bw14
Bw14
 
Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptx
 
Function C++
Function C++ Function C++
Function C++
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
02.adt
02.adt02.adt
02.adt
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Templates2
Templates2Templates2
Templates2
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Templates
TemplatesTemplates
Templates
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 

More from sanya6900

.Net framework
.Net framework.Net framework
.Net frameworksanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
Type conversions
Type conversionsType conversions
Type conversionssanya6900
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Memory allocation
Memory allocationMemory allocation
Memory allocationsanya6900
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03sanya6900
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)sanya6900
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2sanya6900
 

More from sanya6900 (12)

.Net framework
.Net framework.Net framework
.Net framework
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
Type conversions
Type conversionsType conversions
Type conversions
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Ch7
Ch7Ch7
Ch7
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 
Pointers
PointersPointers
Pointers
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 

Templates exception handling

  • 1. Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler
  • 2. 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
  • 3. 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
  • 4. Example void PrintInt( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void PrintChar( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void PrintFloat( float x ) { … } void PrintDouble( double d ) { … } PrintInt(sum); PrintChar(initial); PrintFloat(angle); To output the traced values, we insert:
  • 5. 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.
  • 6. Example of Function Overloading void Print( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void Print( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void Print( float x ) { } Print(someInt); Print(someChar); Print(someFloat); To output the traced values, we insert:
  • 7. 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
  • 8. Example of a Function Template template<class SomeType> void Print( SomeType val ) { cout << "***Debug" << endl; cout << "Value is " << 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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.
  • 14. Instantiating a Class Template // Client code GList<int> list1; GList<float> list2; GList<string> list3; list1.Insert(356); list2.Insert(84.375); list3.Insert("Muffler bolt"); To create lists of different data types GList_int list1; GList_float list2; GList_string list3; template argument Compiler generates 3 distinct class types
  • 15. 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
  • 16. 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++; }
  • 17. Another Template Example: passing two parameters template <class T, int size> class Stack {... }; Stack<int,128> mystack; non-type parameter
  • 18. Exception • An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring at runtime • In C++, a variable or class object that represents an exceptional event.
  • 19. Handling Exception • If without handling, • Program crashes • Falls into unknown state • An exception handler is a section of program code that is designed to execute when a particular exception occurs • Resolve the exception • Lead to known state, such as exiting the program
  • 20. Standard Exceptions Exceptions Thrown by the Language – new Exceptions Thrown by Standard Library Routines Exceptions Thrown by user code, using throw statement
  • 21. The throw Statement Throw: to signal the fact that an exception has occurred; also called raise ThrowStatement throw Expression
  • 22. The try-catch Statement try Block catch (FormalParameter) Block catch (FormalParameter) TryCatchStatement How one part of the program catches and processes the exception that another part of the program throws. FormalParameter DataType VariableName …
  • 23. Example of a try-catch Statement try { // Statements that process personnel data and may throw // exceptions of type int, string, and SalaryError } catch ( int ) { // Statements to handle an int exception } catch ( string s ) { cout << s << endl; // Prints "Invalid customer age" // More statements to handle an age error } catch ( SalaryError ) { // Statements to handle a salary error }
  • 24. Execution of try-catch No statements throw an exception Statement following entire try-catch statement A statement throws an exception Exception Handler Statements to deal with exception are executed Control moves directly to exception handler
  • 25. Throwing an Exception to be Caught by the Calling Code void Func4() { if ( error ) throw ErrType(); } Normal return void Func3() { try { Func4(); } catch ( ErrType ) { } } Function call Return from thrown exception
  • 26. Practice: Dividing by ZERO Apply what you know: int Quotient(int numer, // The numerator int denom ) // The denominator { if (denom != 0) return numer / denom; else //What to do?? do sth. to avoid program //crash }
  • 27. int Quotient(int numer, // The numerator int denom ) // The denominator { if (denom == 0) throw DivByZero(); //throw exception of class DivByZero return numer / denom; } A Solution
  • 28. A Solution // quotient.cpp -- Quotient program #include<iostream.h> #include <string.h> int Quotient( int, int ); class DivByZero {}; // Exception class int main() { int numer; // Numerator int denom; // Denominator //read in numerator and denominator while(cin) { try { cout << "Their quotient: " << Quotient(numer,denom) <<endl; } catch ( DivByZero )//exception handler { cout<<“Denominator can't be 0"<< endl; } // read in numerator and denominator } return 0; }