0% found this document useful (0 votes)
7 views23 pages

Unit 5 Oops

Uploaded by

vishnumnair595
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views23 pages

Unit 5 Oops

Uploaded by

vishnumnair595
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

TEMPLATES AND EXCEPTION HANDLING

Function and Class Templates - Exception Handling – Try-Catch-


Throw Paradigm – Exception Specification – Terminate and Unexpected
Functions – Uncaught Exception.
1. Function and Class Templates
Templates are powerful features of C++.It supports Generic
programming. Templates make it possible to use one function or class to
handle different datatypes.
The concept of templates can be used in two different ways:
i) Function Templates
ii) Class Template
1.1. Function Templates
• A function template works in a similar to a normal function,
with one key difference.
• A single function template can work with different data types at
once but, a single normal function can only work with one set of
data types.
• Function templates can perform the same task for different
datatype, writing less and maintainable code.
• Syntax for function Template
template<class T>
returntype functionname (T arg...)
{
Statements;
}
• template is keyword to create a template
• T- template argument that accepts different data types
• class is a keyword.
• We can also use keyword typename instead of class.

Example 1:
Example 1
#include <iostream>
using namespace std;
// template function
template <class T1>
void display (T1 n1)
{
cout<<n1<<"\n";

}
int main()
{
display("Program");
display("4");
display(5.6);
display('A');
return 0;
}

Output:
Program
4
5.6
A

Example 2:
// If two characters are passed to function template, character with larger ASCII
value is displayed.

#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}

int main()
{
int i1=10, i2=20;
float f1=98.55, f2=87.34;
char c1='a', c2='b';
cout << Large(i1, i2) <<" is larger." << endl;
cout << Large(f1, f2) <<" is larger." << endl;
cout << Large(c1, c2) <<" larger ASCII value.";
return 0;
}
Output:
20 is larger.
98.55 is larger.
b larger ASCII value.

1.1.1. Function template with multiple parameters


We can use more than one generic data type in the template statement.
template<class T1,class T2>
returntype funname( T1 ,T2..)
{
statements;
}

#include <iostream>
using namespace std;
// template function
template <class T1,class T2>
void display (T1 n1, T2 n2)
{
cout<<n1<<"\t"<<n2;

}
int main()
{
display("Program",2);
return 0;
}
Output:
Program 2

1.1.2 Overloading of Template function


A template function may be overloaded either by template function or ordinary
function of its name.
The overloading resolution is accomplished as follows
i) Call an ordinary function that has an exact match.
Ii) Call a template function that could be created with an exact match.
iii) Call the one that matches
An error is generated if no match is found
Example1
#include <iostream>
using namespace std;
// template function
template <class T1,class T2>
void display (T1 n1, T2 n2)
{
cout<<n1<<"\t"<<n2<<endl;

}
template <class T>
void display(T n1)
{
cout<<n1<<endl;
}
int main()
{
display("Program",2);
display("Hello world");
return 0;
}
Output:
Program 2
Hello world

Example2

#include <iostream>
using namespace std;
// template function
template <class T1,class T2>
void display (T1 n1, T2 n2)
{
cout<<n1<<"\t"<<n2<<endl;

}
template <class T>
void display(T n1)
{
cout<<n1<<endl;
}
void display(int x)
{
cout<<"ordinary function "<<x;
}
int main()
{
display("Program",2);
display("Hello world");
display(100);
return 0;
}
Program 2
Hello world
ordinary function 100Int results:

Example 3:
#include <iostream>
using namespace std;

template <typename T>


void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';

cout << "Before passing data to function template.\n";


cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;

Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);

cout << "\n\nAfter passing data to function template.\n";


cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;

return 0;
}

Before passing data to function template.


i1 = 1
i2 = 2
f1 = 1.1
f2 = 2.2
c1 = a
c2 = b

After passing data to function template.


i1 = 2
i2 = 1
f1 = 2.2
f2 = 1.1
c1 = b
c2 = a

1.1.3 Common error-Template:


• No argument template function.
template <class T>
T pop(void)
{
}
• Template type argument unused.
template <class T>
void test(int x)
{
T temp;
}

• Usage of partial number of template arguments.


template<class T,class U>
void insert(T &x)
{
}
Here, the template argument U is not used in argument type.

1.2. Class Template


• We can create class templates for generic class operations. Sometimes,
we need a class implementation that is same for all classes, only the data
types used are different.
• Normally, you would need to create a different class for each data type
OR create different member variables and functions within a single class.
• Syntax:
template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
 T is a template argument which is place holder for the data type used
 Inside the class body, a member variable var and a member function
someOperation() are both of type T.
Create a class template object:
 To create a class template object, you need to define the data type inside a
< > when creation.
 Syntax:
className<dataType> classObject;
Example:
className<int> classObject;
className<float> classObject;
className<string> classObject;

Example1
#include <iostream>
using namespace std;

template <class T>


class cal
{
T a,b;
public:
cal(T a1,T b1)
{
a=a1;
b=b1;
}
void display()
{
cout<<a<<"\t"<<b<<endl;
add();

}
void add()
{
cout<<"Sum is "<<a+b<<endl;
}
};
int main()
{
//className<dataType> classObject;

cal<int> c(2,3);
cal<float> c1(2.5,3.9);
c.display();
c1.display();
return 0;
}

Example2
//calculator class template
#include <iostream>
using namespace std;

template <class T>


class Calculator
{
private:
T num1, num2;

public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}

void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() { return num1 / num2; }


};

int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;


intCalc.displayResult();

cout << endl << "Float results:" << endl;


floatCalc.displayResult();

return 0;
}

Numbers are: 2 and 1.


Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2

Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2

#include <iostream>
using namespace std;
template <class T1=int,class T2=int>
class Test
{
private:
T1 a;
T2 b;

public:
Test(T1 n1, T2 n2)
{
a = n1;
b = n2;
}

void show()
{
cout<<a<<"\t"<<b<<endl;
}
};

int main()
{
Test<float,int> te1(5.6,6);
te1.show();
Test<int,char> te2(4,'r');
te2.show();
Test<> te3(4,'a');
te3.show();
return 0;
}

Output:

5.6 6
4 r
4 97

2. Exception Handling – Try-Catch-Throw Paradigm


• Exceptions are errors that occur run time.
• It refers to unexpected condition in a program.
• The unusual condition could be faults, causing error which in turn
causes the program to fail. Varity of exceptions are
i) Running out of memory.
ii) Not being able to open a file.
iii) Out of bound index.
iv) Initialize the object to impossible value.
• Handling errors at runtime is called Exception handling.
2.1 Two types of Exception
• synchronous Exception : The exception which occur during
program execution ,due to some fault in the input-data or
techniques that is not suitable to handle the current class of data
within the program.
Example: Errors such as out-of-range, overflow.
• Asynchronous Exception: The Exception caused by events or faults
unrelated to the program and beyond the control of the program are
called asynchronous exception.
• Example: keyboard interrupts, hardware malfunctions, disk failure.

2.2. Exception in C++


 Exception handling in c++ is designed to handle only synchronous
exception caused within a program.
 When a program encounters an abnormal situation for which it is
designed, the user may transfer control to some part of the program that is
designed to deal with the problem. This is done by throwing an exception.
 Exception mechanism in c++ works using three keywords.
try, throw, catch.
2.2 Exception Handling Model
• The mechanism suggests that error handling code must perform the
following tasks
i) detect the problem causing exception(hit the exception).
ii) Inform that an error has occurred (throw the exception)
iii) Receive the error information (catch the exception)
iv)Take corrective actions
 The error handling code basically consist of two segments
i) To detect the errors and to throw exception
ii)To catch the exception and to take appropriate action.

2.3 Exception Handling constructs


C++ exception handling mechanism is basically built upon three
keywords namely try, throw and catch.
Syntax:
try
{
throw exception; //blocks of statements which detects and
throws an exception
}
catch(type arg) //catches the exception
{
//block of statements that handles the
exception
}

2.3.1 try construct:


• try keyword defines a boundary within which an exception can
occur.
• The code which can throw any exception is kept inside (or
enclosed in a try block.
• When an exception is detected, it is thrown using a throw statement
in try block.
2.3.2 throw construct:
• When an exception that is desired to be detected, it is thrown using
throw statement in one of the following form.
• When an exception is thrown, it will be caught by the catch
statement associated with the try block.
• The keyword throw is used to raise an exception.
• Syntax
throw T;
throw(exception)
throw exception;
throw; //used for re throwing an exception.
exception may be of any type, including constants.
throw: keyword
T:datatype ,object or by default nothing.
2.3.3. catch block:
• The catch block catches an exception must be immediately follow
the try block that throws an exception.
• When try block throws an exception, the program control leaves
the try block and enters catch block.
• The catch block is an exception handler.
• There may be have multiple catch statements.
• If the type of object thrown matches the arg type in the catch
statement, then catch block is executed for handling the exception.
• If they do not match, the program is aborted with the help of
abort() function which is invoked by default. Exception
Specification.
• When no exception is detected and thrown, the control goes to the
statement immediately after the catch block.
• That is catch block is skipped.
• catch block looks like a function definition.ntype : type of
exception that catch blocks handles. arg : parameter name
Example1:
#include <iostream>
using namespace std;
int main()
{

try
{
throw 4;
}
catch(int a)
{
cout<<"exception caught";
}
return 0;
}
Output:
exception caught

Example2:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter values \n";
cin>>a>>b;
try
{
if(b==0)
throw 2;
else
cout<<"The value is"<<a/b;
}
catch(int i)
{
cout<<"Exception caught :DIVIDE BY ZERO";
}
cout<<"\nEnd of the program";
return 0;
}
 Output1
Enter values
63
The value is2
End of the program
 Output
Enter values
40
Exception caught :DIVIDE BY ZERO
End of the program

2.3.3 Multiple catch statements:


• Program contains multiple catch blocks to handle different types of
exception.
• We have one try statement, we can have many catch statements.
• When an exception is thrown, the exception handlers (catch blocks)
are searched in order for appropriate match.
• The first handler that yields a match is executed.
• After executing the handler(catch), the control goes to the first
statement after the last catch block for that try
• If no match is found, the program gets terminated.
• When the try block does not throw any exception and it completes
normal execution, control passes to the first statement after the last
catch handler associated with that try block.
• Syntax:
try
{
//try block
}
catch(type1 arg)
{
//catch block
}
catch(type2 arg)
{
//catch block
}
catch(typeN arg)
{
//catch block
}
Example1:
#include <iostream>
using namespace std;
int main()
{
int a;
cout<<"Type any number 0 1 -1";
cin>>a;
try
{
if(a==0)
throw 1;
else if(a==-1)
throw 'a';
else
throw 5.6;
}
catch(int i)
{
cout<<"caught integer";
}
catch(char c)
{
cout<<"caught character";
}
catch(double d)
{
cout<<"caught double";
}
return 0;
}
output 1:
Type any number 0 1 -10
caught integer
End of program
Output 2
Type any number 0 1 -1
1
caught double
End of program
Output 3:
Type any number 0 1 -1
-1
caught character
End of program
Output 4:
Type any number 0 1 -1 or more than 1
2
The value of A 2
End of program

2.3.4catch all exception


We can force a catch statement to catch all exception instead of a certain
type alone. catch(…) can be a default statement along with other catch handlers
so that it can catch all those exception which are not handled explicitly.

try
{
//statements;
}
catch(…)
{
//statements;
}
Example1:
#include <iostream>
using namespace std;
int main()
{
int a;
cout<<"Type any number 0 1 -1 or more than 1";
cin>>a;
try
{
if(a==0)
throw 67;
else if(a==-1)
throw 'a';
else if(a==1)
throw 5.6;
else
cout<<"The value of A "<<a;
}
catch(...)
{
cout<<"caught";
}
return 0;
}
Output:
Type any number 0 1 -1 or more than 1
1
caught

2.4 Function invoked by try block throwing exception:

Syntax:
type function(arglist) //function with exception
{
throw(object);//throws exception
}
try
{
invoke function here
}
catch(type arg) //catches exception
{
handles exception here
}

Example 1:
#include <iostream>
using namespace std;
void divide(int x,int y)
{
if(y==0)
{
throw 0;
}
else
{
cout<<"Result"<<x/y<<endl;
}
}
int main()
{
try
{
divide(4,2);
divide(5,0);
}
catch(int i)
{
cout<<"Exception caught"<<endl;
}
return 0;
}
Result 2
Exception caught
3. Exception Specification:
 It is possible to restrict a function to throw only certain specified
exception.
 Syntax:
type function(arglist) throw (type-list)
{
//function body;
}
type-list specifies the type of exception that may be thrown.
 Throwing any other exception will cause abnormal termination.
 To prevent a function from throwing any exception from throwing any
exception,make type-list empty.
throw();
Example:
#include <iostream>
using namespace std;
// only throw ints, chars, and doubles
void f(int val) throw(int,char, double)
{
if(val==0)
throw val;
if(val==1)
throw 'a';
if(val==2)
throw 123.23;
}
int main()
{
try
{
f(0); // also, try passing 1 and 2 to f()
}
catch(int i)
{
cout << "Caught an integer\n";
}
catch(char c)
{
cout << "Caught char\n";
}
catch(double d)
{
cout << "Caught double\n";
}
return 0;
}
output
Caught an integer
4. Uncaught Exception: Terminate and Unexpected Functions

 In some situations, the best way to handle an uncaught exception is to


terminate the program.
 Two special library functions are implemented in C++ to process
exceptions not properly handled by catch blocks or exceptions thrown
outside of a valid try block.
 The Uncaught Exception handling mechanism relies on two libraries
functions
terminate() and unexpected()

terminate():
 In some cases, the exception handling mechanism fails and a call to void
terminate() is made.
 This terminate() call occurs in any of the following situations.
- When terminate() is explicitly called.
- When no catch can be matched to a thrown object.
- When the stack becomes corrupted during the exception-
handling process.
- When a system defined unexpected() is called.
 The function terminate() is invoked when an exception is raised and
handler is not found.
 The default action for terminate is to invoke abort().
 Such a default action causes immediate termination of program
execution.
unexpected()
 When a function with an exception specification throws an exception that
is not listed in its exception specification, the function void unexpected()
is called.
 By default, unexpected() calls the function terminate().
 The terminate() function calls a function specified by the set_terminate()
function. By default, terminate calls abort() , which exits from the
program.
 A terminate function cannot return to its caller, either by using return or
by throwing an exception
set_terminate():
 The set_terminate() function allows the user to install a function that
defines program actions to be taken to terminate the program when a
handler for an exception cannot be found.
Example:
#include <iostream>
using namespace std;
int main()
{

try
{
throw 4.5;
}
catch(int a)
{
cout<<"exception caught";
}
return 0;
}

terminate called after throwing an instance of 'double'

set_terminate:

#include <iostream>
using namespace std;
void myter()
{
cout<<"myterminate invoked";
exit(1);
}
int main()
{
set_terminate(myter);

try
{
throw 4.5;
}
catch(int a)
{
cout<<"exception caught";
}
return 0;
}
Output:
myterminate invoked Output:
myterminate invoked

unexpected()
 The unexpected() function is called when a function throws an exception
not listed in its exception specification.
 The program calls unexpected() which calls any user-defined function
registered by set_unexpected.
 If no function is registered with set_unexpected,the unexpected() function
then invokes the terminate() function.
set_unexpected()
 The function set_unexpected() lets the user to install a function that
defines the program actions to be taken when a function throws an
exception not listed in its exception specification.
 The actions are defined in unexpected_fun() library function.
 By default, an unexpected exception causes unexpected() to be called
,which in turn calls unexpected_fun
 The unexpected_func() can invoke abort(),exit() or terminate() functions.
Uncaught exception-cont:

 Special function to handle uncaught exception in a systematic manner


 i)set_terminate()
 ii)set_unexpected()
 The terminate() is a library function which by default aborts the program.
- It is called whenever the exception handling mechanism cannot find a
handler for a thrown exception.
- The unexpected() is called when a function with an exception
specification throws an exception of a type that is not listed in the
exception specification for the function
- A function declaration without a specification like throw(char*) may
throw any type of exception, and one with throw() is not allowed to throw
exceptions at all.
- By default unexpected() calls terminate().
 throw without a catch results in call to terminate or the function set for it.
 When a exception thrown does not match the exception specification
results in a call to unexpected or the function set for it.
 f no exception is presently being handled, executing a throw-expression
with no operand calls terminate()
#include <iostream>
using namespace std;

// only throw chars, and doubles


void f(int val) throw(char, double)
{
if(val==0)
throw val;
if(val==1)
throw 'a';
if(val==2)
throw 123.23;
}
void Myunexpected()
{
cout<<"My unexpected handler is invoked";
exit(1);
}
int main()
{
set_unexpected(Myunexpected);
try
{
f(0); // also, try passing 1 and 2 to f()
}
catch(int i)
{
cout << "Caught an integer\n";
}
catch(char c)
{
cout << "Caught char\n";
}
catch(double d)
{
cout << "Caught double\n";
}
return 0;
}
Output:
My unexpected handler is invoked

You might also like