SlideShare a Scribd company logo
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 (20)

PPTX
Java generics
Hosein Zare
 
PDF
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
PPT
Introduction to Java Programming Part 2
university of education,Lahore
 
PPT
Generic Programming seminar
Gautam Roy
 
PPT
Java Generics for Dummies
knutmork
 
PPT
Templates
Nilesh Dalvi
 
PPTX
Operators in java
Then Murugeshwari
 
PPTX
C formatted and unformatted input and output constructs
GopikaS12
 
PPTX
Modern C++
Richard Thomson
 
PPTX
Storage classes in C
Nitesh Bichwani
 
PPTX
12. Exception Handling
Intro C# Book
 
PDF
Implicit conversion and parameters
Knoldus Inc.
 
DOCX
Java programs
Dr.M.Karthika parthasarathy
 
PDF
Java Simple Programs
Upender Upr
 
PPT
Scala functions
Knoldus Inc.
 
PDF
Python Programming
Sreedhar Chowdam
 
PPTX
Storage class in C Language
Nitesh Kumar Pandey
 
ODP
(2) c sharp introduction_basics_part_i
Nico Ludwig
 
PPT
Simple Java Programs
AravindSankaran
 
PPT
02basics
Waheed Warraich
 
Java generics
Hosein Zare
 
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
Introduction to Java Programming Part 2
university of education,Lahore
 
Generic Programming seminar
Gautam Roy
 
Java Generics for Dummies
knutmork
 
Templates
Nilesh Dalvi
 
Operators in java
Then Murugeshwari
 
C formatted and unformatted input and output constructs
GopikaS12
 
Modern C++
Richard Thomson
 
Storage classes in C
Nitesh Bichwani
 
12. Exception Handling
Intro C# Book
 
Implicit conversion and parameters
Knoldus Inc.
 
Java Simple Programs
Upender Upr
 
Scala functions
Knoldus Inc.
 
Python Programming
Sreedhar Chowdam
 
Storage class in C Language
Nitesh Kumar Pandey
 
(2) c sharp introduction_basics_part_i
Nico Ludwig
 
Simple Java Programs
AravindSankaran
 
02basics
Waheed Warraich
 

Viewers also liked (20)

PPTX
Templates in C++
Tech_MX
 
PPTX
Templates in c++
Mayank Bhatt
 
PPTX
Exception handling
Abhishek Pachisia
 
PPT
Exception handling in c++ by manoj vasava
Manoj_vasava
 
DOCX
C++ Template
Saket Pathak
 
PPSX
Exception Handling
Reddhi Basu
 
PPTX
functions of C++
tarandeep_kaur
 
PPTX
Inheritance in C++
Laxman Puri
 
PPT
14 operator overloading
Docent Education
 
PPSX
Cisco Industry template - 4x3 dark
KVEDesign
 
PPTX
Function class in c++
Kumar
 
PDF
Programming in c++
Baljit Saini
 
PPT
Standard Template Library
Kumar Gaurav
 
PPT
C++ overloading
sanya6900
 
PPTX
Analog Electronics ppt on Transition & diffusion capacitance by Being topper
Vipin Kumar
 
ODP
Java Generics
Carol McDonald
 
PPTX
Managing console input and output
gourav kottawar
 
PDF
C++ Advanced Features (TCF 2014)
Michael Redlich
 
PPTX
Inheritance in c++
Paumil Patel
 
PDF
Lexical analysis
Richa Sharma
 
Templates in C++
Tech_MX
 
Templates in c++
Mayank Bhatt
 
Exception handling
Abhishek Pachisia
 
Exception handling in c++ by manoj vasava
Manoj_vasava
 
C++ Template
Saket Pathak
 
Exception Handling
Reddhi Basu
 
functions of C++
tarandeep_kaur
 
Inheritance in C++
Laxman Puri
 
14 operator overloading
Docent Education
 
Cisco Industry template - 4x3 dark
KVEDesign
 
Function class in c++
Kumar
 
Programming in c++
Baljit Saini
 
Standard Template Library
Kumar Gaurav
 
C++ overloading
sanya6900
 
Analog Electronics ppt on Transition & diffusion capacitance by Being topper
Vipin Kumar
 
Java Generics
Carol McDonald
 
Managing console input and output
gourav kottawar
 
C++ Advanced Features (TCF 2014)
Michael Redlich
 
Inheritance in c++
Paumil Patel
 
Lexical analysis
Richa Sharma
 
Ad

Similar to Templates exception handling (20)

PPT
UNIT III.ppt
Ajit Mali
 
PPT
UNIT III (2).ppt
VGaneshKarthikeyan
 
PPTX
Object Oriented Design and Programming Unit-04
Sivakumar M
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
DOCX
unit 5.docx...............................
nikhithanikky1212
 
PPTX
Presentation on template and exception
Sajid Alee Mosavi
 
PPTX
Pre zen ta sion
Sajid Alee Mosavi
 
PDF
Object Oriented Programming using C++ - Part 5
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PDF
Week 02_Development Environment of C++.pdf
salmankhizar3
 
PPTX
Templates and Exception Handling in C++
Nimrita Koul
 
PPT
2.overview of c++ ________lecture2
Warui Maina
 
PPTX
TEMPLATES IN JAVA
MuskanSony
 
PDF
A tutorial on C++ Programming
Prof. Erwin Globio
 
PPT
C++ Language
Syed Zaid Irshad
 
PPTX
Silde of the cse fundamentals a deep analysis
Rayhan331
 
PDF
c++ referesher 1.pdf
AnkurSingh656748
 
PPT
Exception handling and templates
farhan amjad
 
PPTX
OOPS USING C++(UNIT 2)
Dr. SURBHI SAROHA
 
UNIT III.ppt
Ajit Mali
 
UNIT III (2).ppt
VGaneshKarthikeyan
 
Object Oriented Design and Programming Unit-04
Sivakumar M
 
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
unit 5.docx...............................
nikhithanikky1212
 
Presentation on template and exception
Sajid Alee Mosavi
 
Pre zen ta sion
Sajid Alee Mosavi
 
Object Oriented Programming using C++ - Part 5
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Week 02_Development Environment of C++.pdf
salmankhizar3
 
Templates and Exception Handling in C++
Nimrita Koul
 
2.overview of c++ ________lecture2
Warui Maina
 
TEMPLATES IN JAVA
MuskanSony
 
A tutorial on C++ Programming
Prof. Erwin Globio
 
C++ Language
Syed Zaid Irshad
 
Silde of the cse fundamentals a deep analysis
Rayhan331
 
c++ referesher 1.pdf
AnkurSingh656748
 
Exception handling and templates
farhan amjad
 
OOPS USING C++(UNIT 2)
Dr. SURBHI SAROHA
 
Ad

More from sanya6900 (12)

PPT
.Net framework
sanya6900
 
PPT
INTRODUCTION TO IIS
sanya6900
 
PPT
INTRODUCTION TO IIS
sanya6900
 
PPT
Type conversions
sanya6900
 
PPT
operators and expressions in c++
sanya6900
 
PPT
Memory allocation
sanya6900
 
PPT
File handling in_c
sanya6900
 
PPT
Ch7
sanya6900
 
PPT
Cpphtp4 ppt 03
sanya6900
 
PPT
Inheritance (1)
sanya6900
 
PPT
Pointers
sanya6900
 
PPT
C cpluplus 2
sanya6900
 
.Net framework
sanya6900
 
INTRODUCTION TO IIS
sanya6900
 
INTRODUCTION TO IIS
sanya6900
 
Type conversions
sanya6900
 
operators and expressions in c++
sanya6900
 
Memory allocation
sanya6900
 
File handling in_c
sanya6900
 
Cpphtp4 ppt 03
sanya6900
 
Inheritance (1)
sanya6900
 
Pointers
sanya6900
 
C cpluplus 2
sanya6900
 

Recently uploaded (20)

PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PDF
SG1-ALM-MS-EL-30-0008 (00) MS - Isolators and disconnecting switches.pdf
djiceramil
 
PDF
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
PPTX
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
PDF
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
PPTX
quantum computing transition from classical mechanics.pptx
gvlbcy
 
PDF
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PPTX
cybersecurityandthe importance of the that
JayachanduHNJc
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
SG1-ALM-MS-EL-30-0008 (00) MS - Isolators and disconnecting switches.pdf
djiceramil
 
Jual GPS Geodetik CHCNAV i93 IMU-RTK Lanjutan dengan Survei Visual
Budi Minds
 
Introduction to Fluid and Thermal Engineering
Avesahemad Husainy
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
MULTI LEVEL DATA TRACKING USING COOJA.pptx
dollysharma12ab
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
Air -Powered Car PPT by ER. SHRESTH SUDHIR KOKNE.pdf
SHRESTHKOKNE
 
quantum computing transition from classical mechanics.pptx
gvlbcy
 
STUDY OF NOVEL CHANNEL MATERIALS USING III-V COMPOUNDS WITH VARIOUS GATE DIEL...
ijoejnl
 
Zero Carbon Building Performance standard
BassemOsman1
 
cybersecurityandthe importance of the that
JayachanduHNJc
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 

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; }