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.
 Errors can be dealt with at place error occurs
 Easy to see if proper error checking implemented
 Harder to read application itself and see how code works
 Exception handling
 Makes clear, robust, fault-tolerant programs
 C++ removes error handling code from "main line" of program
 Common failures
 new not allocating memory
 Out of bounds array subscript
 Division by zero
 Invalid function parameters
 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
 Typically used when error dealt with in different place than
where it occurred
 Useful when program cannot recover but must shut down
cleanly
 Exception handling should not be used for program
control
 Not optimized, can harm program performance
 Exception handling improves fault-tolerance
 Easier to write error-processing code
 Specify what type of exceptions are to be caught
 Most programs support only single threads
 Techniques in this chapter apply for multithreaded OS as well
(windows NT, OS/2, some UNIX)
 Exception handling another way to return control from
a function or block of code
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
When Exception Handling Should Be
Used
 Error handling should be used for
 Processing exceptional situations
 Processing exceptions for components that cannot handle
them directly
 Processing exceptions for widely used components (libraries,
classes, functions) that should not process their own
exceptions
 Large projects that require uniform error processing
Basics of C++ Exception Handling: try,
throw, catch
 A function can throw an exception object if it detects
an error
 Object typically a character string (error message) or
class object
 If exception handler exists, exception caught and
handled
 Otherwise, program terminates
Basics of C++ Exception Handling:
try, throw, catch (II)
 Format
 Enclose code that may have an error in try block
 Follow with one or more catch blocks
– Each catch block has an exception handler
 If exception occurs and matches parameter in catch
block, code in catch block executed
 If no exception thrown, exception handlers skipped and
control resumes after catch blocks
 throw point - place where exception occurred
– Control cannot return to throw point
 throw - indicates an exception has occurred
 Usually has one operand (sometimes zero) of any type
– If operand an object, called an exception object
– Conditional expression can be thrown
 Code referenced in a try block can throw an exception
 Exception caught by closest exception handler
 Control exits current try block and goes to catch
handler (if it exists)
 Example (inside function definition)
if ( denominator == 0 )
throw DivideByZeroException();
– Throws a dividebyzeroexception object
The throw Statement
Throw: to signal the fact that an
exception has occurred; also called
raise
ThrowStatement throw Expression
 Exception handlers are in catch blocks
 Format: catch( exceptionType parameterName){
exception handling code
}
 Caught if argument type matches throw type
 If not caught then terminate called which (by default)
calls abort
 Example:
catch ( DivideByZeroException ex) {
cout << "Exception occurred: " << ex.what() <<'n'
}
– Catches exceptions of type DivideByZeroException
 Catch all exceptions
catch(...) - catches all exceptions
– You do not know what type of exception occurred
– There is no parameter name - cannot reference the object
 If no handler matches thrown object
 Searches next enclosing try block
– If none found, terminate called
 If found, control resumes after last catch block
 If several handlers match thrown object, first one found
is executed
 catch parameter matches thrown object when
 They are of the same type
– Exact match required - no promotions/conversions
allowed
 The catch parameter is a public base class of the
thrown object
 The catch parameter is a base-class pointer/
reference type and the thrown object is a derived-class
pointer/ reference type
 The catch handler is catch( ... )
 Thrown const objects have const in the parameter
type
 Unreleased resources
 Resources may have been allocated when exception
thrown
 catch handler should delete space allocated by new
and close any opened files
 catch handlers can throw exceptions
 Exceptions can only be processed by outer try blocks
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;
}
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
 An exception is a unusual, often unpredictable event that
requires special processing occurring at runtime
– throw
– try-catch
 Rethrowing exceptions
 Used when an exception handler cannot process an
exception
 Rethrow exception with the statement:
throw;
– No arguments
– If no exception thrown in first place, calls terminate
 Handler can always rethrow exception, even if it
performed some processing
 Rethrown exception detected by next enclosing try block
1. Load header
1.1 Function prototype
1 // Fig. 23.2: fig23_02.cpp
2 // Demonstration of rethrowing an exception.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 #include <exception>
9
10 using std::exception;
11
12 void throwException()
13 {
14 // Throw an exception and immediately catch it.
15 try {
16 cout << "Function throwExceptionn";
17 throw exception(); // generate exception
18 }
19 catch( exception e )
20 {
21 cout << "Exception handled in function throwExceptionn";
2. Function call
3. Output
22 throw; // rethrow exception for further processing
23 }
24
25 cout << "This also should not printn";
26 }
27
28 int main()
29 {
30 try {
31 throwException();
32 cout << "This should not printn";
33 }
34 catch ( exception e )
35 {
36 cout << "Exception handled in mainn";
37 }
38
39 cout << "Program control continues after catch in main"
40 << endl;
41 return 0;
42 }
Function throwException
Exception handled in function throwException
Exception handled in main
Program control continues after catch in main
 Exception specification (throw list)
 Lists exceptions that can be thrown by a function
Example:
int g( double h ) throw ( a, b, c )
{
// function body
}
 Function can throw listed exceptions or derived types
 If other type thrown, function unexpected called
 throw() (i.e., no throw list) states that function will not throw any
exceptions
– In reality, function can still throw exceptions, but calls unexpected
(more later)
 If no throw list specified, function can throw any exception
 Function unexpected
 Calls the function specified with set_unexpected
– Default: terminate
 Function terminate
 Calls function specified with set_terminate
– Default: abort
 set_terminate and set_unexpected
 Prototypes in <exception>
 Take pointers to functions (i.E., Function name)
– Function must return void and take no arguments
 Returns pointer to last function called by terminate or unexpected
Uncaught Exception
 Function-call stack unwound when exception
thrown and not caught in a particular scope
 Tries to catch exception in next outer try/catch
block
 Function in which exception was not caught
terminates
–Local variables destroyed
–Control returns to place where function was
called
 If control returns to a try block, attempt made to
catch exception
–Otherwise, further unwinds stack
 If exception not caught, terminate called
Constructors, Destructors and
Exception Handling
 What to do with an error in a constructor?
 A constructor cannot return a value - how do we let
the outside world know of an error?
– Keep defective object and hope someone tests it
– Set some variable outside constructor
 A thrown exception can tell outside world about a
failed constructor
 catch handler must have a copy constructor for
thrown object
Ad

More Related Content

Similar to UNIT III (2).ppt (20)

$Cash
$Cash$Cash
$Cash
ErandaMoney
 
$Cash
$Cash$Cash
$Cash
ErandaMoney
 
Unit iii pds
Unit iii pdsUnit iii pds
Unit iii pds
Kongunadu College of Engineering and Technology
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
ZenLooper
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
Diana Gray, MBA
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
Mahmoud Ouf
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
Jyothishmathi Institute of Technology and Science Karimnagar
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
Syed Bahadur Shah
 
Programming with C++
Programming with C++Programming with C++
Programming with C++
ssuser802d47
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
VishuSaini22
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
ZenLooper
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
RPA Summer School Studio Session 4 AMER: Advanced practices with Studio and O...
Diana Gray, MBA
 
Exception handling with python class 12.pptx
Exception handling with python class 12.pptxException handling with python class 12.pptx
Exception handling with python class 12.pptx
PreeTVithule1
 
Programming with C++
Programming with C++Programming with C++
Programming with C++
ssuser802d47
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
VishuSaini22
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
sanya6900
 

More from VGaneshKarthikeyan (20)

1.3 Basic coding skills_fundamentals .ppt
1.3 Basic coding skills_fundamentals .ppt1.3 Basic coding skills_fundamentals .ppt
1.3 Basic coding skills_fundamentals .ppt
VGaneshKarthikeyan
 
5_Model for Predictions_Machine_Learning.ppt
5_Model for Predictions_Machine_Learning.ppt5_Model for Predictions_Machine_Learning.ppt
5_Model for Predictions_Machine_Learning.ppt
VGaneshKarthikeyan
 
2_Errors in Experimental Observations_ML.ppt
2_Errors in Experimental Observations_ML.ppt2_Errors in Experimental Observations_ML.ppt
2_Errors in Experimental Observations_ML.ppt
VGaneshKarthikeyan
 
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdfFINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
VGaneshKarthikeyan
 
FINAL_DAY10_INTERFACES_roles and benefits.pptx
FINAL_DAY10_INTERFACES_roles and benefits.pptxFINAL_DAY10_INTERFACES_roles and benefits.pptx
FINAL_DAY10_INTERFACES_roles and benefits.pptx
VGaneshKarthikeyan
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptxFINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
VGaneshKarthikeyan
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
Java ppt-class_Introduction_class_Objects.ppt
Java ppt-class_Introduction_class_Objects.pptJava ppt-class_Introduction_class_Objects.ppt
Java ppt-class_Introduction_class_Objects.ppt
VGaneshKarthikeyan
 
INT104 DBMS - Introduction_Atomicity.ppt
INT104 DBMS - Introduction_Atomicity.pptINT104 DBMS - Introduction_Atomicity.ppt
INT104 DBMS - Introduction_Atomicity.ppt
VGaneshKarthikeyan
 
6. Implementation of classes_and_its_advantages.pdf
6. Implementation of classes_and_its_advantages.pdf6. Implementation of classes_and_its_advantages.pdf
6. Implementation of classes_and_its_advantages.pdf
VGaneshKarthikeyan
 
Operators_in_C++_advantages_applications.ppt
Operators_in_C++_advantages_applications.pptOperators_in_C++_advantages_applications.ppt
Operators_in_C++_advantages_applications.ppt
VGaneshKarthikeyan
 
1_Standard error Experimental Data_ML.ppt
1_Standard error Experimental Data_ML.ppt1_Standard error Experimental Data_ML.ppt
1_Standard error Experimental Data_ML.ppt
VGaneshKarthikeyan
 
Unit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptxUnit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptx
VGaneshKarthikeyan
 
Linear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptxLinear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptx
VGaneshKarthikeyan
 
K-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptxK-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptx
VGaneshKarthikeyan
 
Numpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptxNumpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptx
VGaneshKarthikeyan
 
Refined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.pptRefined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.ppt
VGaneshKarthikeyan
 
randomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.pptrandomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.ppt
VGaneshKarthikeyan
 
stochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.pptstochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.ppt
VGaneshKarthikeyan
 
1.3 Basic coding skills_fundamentals .ppt
1.3 Basic coding skills_fundamentals .ppt1.3 Basic coding skills_fundamentals .ppt
1.3 Basic coding skills_fundamentals .ppt
VGaneshKarthikeyan
 
5_Model for Predictions_Machine_Learning.ppt
5_Model for Predictions_Machine_Learning.ppt5_Model for Predictions_Machine_Learning.ppt
5_Model for Predictions_Machine_Learning.ppt
VGaneshKarthikeyan
 
2_Errors in Experimental Observations_ML.ppt
2_Errors in Experimental Observations_ML.ppt2_Errors in Experimental Observations_ML.ppt
2_Errors in Experimental Observations_ML.ppt
VGaneshKarthikeyan
 
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdfFINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
VGaneshKarthikeyan
 
FINAL_DAY10_INTERFACES_roles and benefits.pptx
FINAL_DAY10_INTERFACES_roles and benefits.pptxFINAL_DAY10_INTERFACES_roles and benefits.pptx
FINAL_DAY10_INTERFACES_roles and benefits.pptx
VGaneshKarthikeyan
 
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptxFINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
VGaneshKarthikeyan
 
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptxFINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
VGaneshKarthikeyan
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
Java ppt-class_Introduction_class_Objects.ppt
Java ppt-class_Introduction_class_Objects.pptJava ppt-class_Introduction_class_Objects.ppt
Java ppt-class_Introduction_class_Objects.ppt
VGaneshKarthikeyan
 
INT104 DBMS - Introduction_Atomicity.ppt
INT104 DBMS - Introduction_Atomicity.pptINT104 DBMS - Introduction_Atomicity.ppt
INT104 DBMS - Introduction_Atomicity.ppt
VGaneshKarthikeyan
 
6. Implementation of classes_and_its_advantages.pdf
6. Implementation of classes_and_its_advantages.pdf6. Implementation of classes_and_its_advantages.pdf
6. Implementation of classes_and_its_advantages.pdf
VGaneshKarthikeyan
 
Operators_in_C++_advantages_applications.ppt
Operators_in_C++_advantages_applications.pptOperators_in_C++_advantages_applications.ppt
Operators_in_C++_advantages_applications.ppt
VGaneshKarthikeyan
 
1_Standard error Experimental Data_ML.ppt
1_Standard error Experimental Data_ML.ppt1_Standard error Experimental Data_ML.ppt
1_Standard error Experimental Data_ML.ppt
VGaneshKarthikeyan
 
Unit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptxUnit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptx
VGaneshKarthikeyan
 
Linear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptxLinear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptx
VGaneshKarthikeyan
 
K-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptxK-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptx
VGaneshKarthikeyan
 
Numpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptxNumpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptx
VGaneshKarthikeyan
 
Refined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.pptRefined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.ppt
VGaneshKarthikeyan
 
randomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.pptrandomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.ppt
VGaneshKarthikeyan
 
stochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.pptstochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.ppt
VGaneshKarthikeyan
 
Ad

Recently uploaded (20)

AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Ad

UNIT III (2).ppt

  • 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.  Errors can be dealt with at place error occurs  Easy to see if proper error checking implemented  Harder to read application itself and see how code works  Exception handling  Makes clear, robust, fault-tolerant programs  C++ removes error handling code from "main line" of program  Common failures  new not allocating memory  Out of bounds array subscript  Division by zero  Invalid function parameters
  • 20.  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  Typically used when error dealt with in different place than where it occurred  Useful when program cannot recover but must shut down cleanly  Exception handling should not be used for program control  Not optimized, can harm program performance
  • 21.  Exception handling improves fault-tolerance  Easier to write error-processing code  Specify what type of exceptions are to be caught  Most programs support only single threads  Techniques in this chapter apply for multithreaded OS as well (windows NT, OS/2, some UNIX)  Exception handling another way to return control from a function or block of code
  • 22. 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
  • 23. Standard Exceptions  Exceptions Thrown by the Language – new  Exceptions Thrown by Standard Library Routines  Exceptions Thrown by user code, using throw statement
  • 24. When Exception Handling Should Be Used  Error handling should be used for  Processing exceptional situations  Processing exceptions for components that cannot handle them directly  Processing exceptions for widely used components (libraries, classes, functions) that should not process their own exceptions  Large projects that require uniform error processing
  • 25. Basics of C++ Exception Handling: try, throw, catch  A function can throw an exception object if it detects an error  Object typically a character string (error message) or class object  If exception handler exists, exception caught and handled  Otherwise, program terminates
  • 26. Basics of C++ Exception Handling: try, throw, catch (II)  Format  Enclose code that may have an error in try block  Follow with one or more catch blocks – Each catch block has an exception handler  If exception occurs and matches parameter in catch block, code in catch block executed  If no exception thrown, exception handlers skipped and control resumes after catch blocks  throw point - place where exception occurred – Control cannot return to throw point
  • 27.  throw - indicates an exception has occurred  Usually has one operand (sometimes zero) of any type – If operand an object, called an exception object – Conditional expression can be thrown  Code referenced in a try block can throw an exception  Exception caught by closest exception handler  Control exits current try block and goes to catch handler (if it exists)  Example (inside function definition) if ( denominator == 0 ) throw DivideByZeroException(); – Throws a dividebyzeroexception object
  • 28. The throw Statement Throw: to signal the fact that an exception has occurred; also called raise ThrowStatement throw Expression
  • 29.  Exception handlers are in catch blocks  Format: catch( exceptionType parameterName){ exception handling code }  Caught if argument type matches throw type  If not caught then terminate called which (by default) calls abort  Example: catch ( DivideByZeroException ex) { cout << "Exception occurred: " << ex.what() <<'n' } – Catches exceptions of type DivideByZeroException
  • 30.  Catch all exceptions catch(...) - catches all exceptions – You do not know what type of exception occurred – There is no parameter name - cannot reference the object  If no handler matches thrown object  Searches next enclosing try block – If none found, terminate called  If found, control resumes after last catch block  If several handlers match thrown object, first one found is executed
  • 31.  catch parameter matches thrown object when  They are of the same type – Exact match required - no promotions/conversions allowed  The catch parameter is a public base class of the thrown object  The catch parameter is a base-class pointer/ reference type and the thrown object is a derived-class pointer/ reference type  The catch handler is catch( ... )  Thrown const objects have const in the parameter type
  • 32.  Unreleased resources  Resources may have been allocated when exception thrown  catch handler should delete space allocated by new and close any opened files  catch handlers can throw exceptions  Exceptions can only be processed by outer try blocks
  • 33. 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 …
  • 34. 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 }
  • 35. 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
  • 36. 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
  • 37. 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 }
  • 38. 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
  • 39. 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; }
  • 40. 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  An exception is a unusual, often unpredictable event that requires special processing occurring at runtime – throw – try-catch
  • 41.  Rethrowing exceptions  Used when an exception handler cannot process an exception  Rethrow exception with the statement: throw; – No arguments – If no exception thrown in first place, calls terminate  Handler can always rethrow exception, even if it performed some processing  Rethrown exception detected by next enclosing try block
  • 42. 1. Load header 1.1 Function prototype 1 // Fig. 23.2: fig23_02.cpp 2 // Demonstration of rethrowing an exception. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <exception> 9 10 using std::exception; 11 12 void throwException() 13 { 14 // Throw an exception and immediately catch it. 15 try { 16 cout << "Function throwExceptionn"; 17 throw exception(); // generate exception 18 } 19 catch( exception e ) 20 { 21 cout << "Exception handled in function throwExceptionn";
  • 43. 2. Function call 3. Output 22 throw; // rethrow exception for further processing 23 } 24 25 cout << "This also should not printn"; 26 } 27 28 int main() 29 { 30 try { 31 throwException(); 32 cout << "This should not printn"; 33 } 34 catch ( exception e ) 35 { 36 cout << "Exception handled in mainn"; 37 } 38 39 cout << "Program control continues after catch in main" 40 << endl; 41 return 0; 42 } Function throwException Exception handled in function throwException Exception handled in main Program control continues after catch in main
  • 44.  Exception specification (throw list)  Lists exceptions that can be thrown by a function Example: int g( double h ) throw ( a, b, c ) { // function body }  Function can throw listed exceptions or derived types  If other type thrown, function unexpected called  throw() (i.e., no throw list) states that function will not throw any exceptions – In reality, function can still throw exceptions, but calls unexpected (more later)  If no throw list specified, function can throw any exception
  • 45.  Function unexpected  Calls the function specified with set_unexpected – Default: terminate  Function terminate  Calls function specified with set_terminate – Default: abort  set_terminate and set_unexpected  Prototypes in <exception>  Take pointers to functions (i.E., Function name) – Function must return void and take no arguments  Returns pointer to last function called by terminate or unexpected
  • 46. Uncaught Exception  Function-call stack unwound when exception thrown and not caught in a particular scope  Tries to catch exception in next outer try/catch block  Function in which exception was not caught terminates –Local variables destroyed –Control returns to place where function was called  If control returns to a try block, attempt made to catch exception –Otherwise, further unwinds stack  If exception not caught, terminate called
  • 47. Constructors, Destructors and Exception Handling  What to do with an error in a constructor?  A constructor cannot return a value - how do we let the outside world know of an error? – Keep defective object and hope someone tests it – Set some variable outside constructor  A thrown exception can tell outside world about a failed constructor  catch handler must have a copy constructor for thrown object