Oop Unit 5
Oop Unit 5
UNIT-V
Exception Handling and Templates
1
Contents
● Exception Handling- Fundamentals, other error handling techniques, simple
exception handling- Divide by Zero, Multiple catching, re-throwing an
exception, exception specifications, user defined exceptions, processing
unexpected exceptions, constructor, destructor and exception handling,
exception and inheritance.
● Templates- The Power of Templates, Function template, overloading
Function templates, and class template, class template and Nontype
parameters, template and friends Generic Functions, The type name and
export keywords.
Exception Handling and Templates
Fundamentals
● The process of converting system error messages into user friendly error message is known as
Exception handling.
● This is one of the powerful feature of C++ to handle runtime error and maintain normal flow of
c++ application
● It is an event which occurs during the execution of a program, that disrupts the normal flow of
programs instructions
C++ exception handling is built upon three keywords: try, catch and throw.
● throw − A program throws an exception when a problem shows up. This is done using a
throw keyword.
● catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
● try − A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination
of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code.
Exception Handling and Templates
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in different
situations.
Exception Handling and Templates
Multiple Catch Statement
A single try statement can have multiple catch statements. Execution of particular catch block depends on
the type of exception thrown by the throw keyword. If throw keyword send exception of integer type, catch
block with integer parameter will get execute.
#include<iostream.h> catch(int a)
#include<conio.h> {
void main() cout<<"\nInteger exception caught.";
{ }
int a=2; catch(char ch)
{
try cout<<"\nCharacter exception caught.";
{ }
catch(double d)
if(a= =1) {
throw a; //throwing integer exception cout<<"\nDouble exception caught.";
}
else if(a= =2)
throw 'A'; //throwing character exception cout<<"\nEnd of program.";
#include<iostream.h>
#include<conio.h> else if(a= =3)
void main() throw 4.5; //throwing float exception
{
int a=1; }
catch(...)
try {
{ cout<<"\nException occur.";
}
if(a= =1)
throw a; //throwing integer exception cout<<"\nEnd of program.";
Exception occur.
End of program.
Divide by Zero exception
// C++ program to demonstrate the use of try,catch
// calculate result if no exception
and throw in exception handling.
occurs
#include <iostream>
res = numerator / denominator;
#include <stdexcept>
//[printing result after
using namespace std;
division
cout << "Result after
int main()
division: " << res << endl;
{
} // Try close
// try block
// catch block to catch the thrown
try {
exception
int numerator = 10;
catch (const exception& e) {
int denominator = 0;
// print the exception
int res;
cout << "Exception " <<
// check if denominator is 0 then throw runtime
e.what() << endl;
error
}
if (denominator == 0)
{
return 0;
throw runtime_error("Division by zero not
}
allowed!");
}
Output:
Exception Division by zero not allowed!
Rethrowing Exceptions
Rethrowing exception is possible, where we have an inner and outer try-catch statements
(Nested try-catch). An exception to be thrown from inner catch block to outer catch block is
called rethrowing exception.
Rethrowing Exceptions
#include<iostream.h> catch(int n)
#include<conio.h> {
void main() cout<<"\nException in outer try-catch block.";
{ }
int a=1;
cout<<"\nEnd of program.";
try
{ }
try
{ Output :
throw a;
} Exception in inner try-catch block.
catch(int x) Exception in outer try-catch block.
{ End of program.
cout<<"\nException in inner try-catch block.";
throw x;
}
}
User Defined Exception
We can use Exception handling with class too. Even we can throw an exception of user defined class
types. For throwing an exception of say demo class type within try block we may write- throw demo();
#include <iostream>
using namespace std;
class demo
{
};
int main()
{
try
{
throw demo();
}
catch (demo d)
{
cout << "Caught exception of demo class \n";
}
Exception and Inheritance
Exception handling can also be implemented with the help of inheritance. In case of inheritance object
thrown by derived class is caught by the first catch block.
#include <iostream> catch (demo1 d1)
using namespace std; {
class demo1 cout << "Caught exception of demo1 class \n";
{ }
}; catch (demo2 d2)
class demo2 : public demo1 {
{ cout << "Caught exception of demo2 class \n";
}; }
}
int main() }
{
for (int i = 1; i <= 2; i++)
{ Output:-
try Caught exception of demo1 class
{ Caught exception of demo1 class
if (i == 1)
throw demo1();
else if (i == 2)
throw demo2();
}
Exception Handling with Constructor
Exception handling can also be implemented by using constructor. Though we cannot return any value from the
constructor but with the help of try and catch block we can.
#include <iostream> void show()
using namespace std; {
cout << "Num = " << num << endl;
class demo }
{ };
int num;
public: int main()
demo(int x) {
{
try // constructor will be called
{ demo(0);
cout << "Again creating object \n";
if (x == 0) demo(1);
}
// catch block would be called
throw "Zero not allowed ";
num = x;
show();
}
catch (const char* exp) {
cout << "Exception caught \n ";
cout << exp << endl;
}
}
Destructor and Exception Handling
Destructors in C++ basically called when objects will get destroyed and release memory from the system. When an
exception is thrown in the class, the destructor is called automatically before the catch block gets executed.
}
Templates
A template is a simple and yet very powerful tool in C++.
The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data
types.
For example, a software company may need sort() for different data types.
Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a
parameter.
Generic Programming
•It’s a programming style, where one algorithm is designed to perform specific task,
without considering specific data type to operate.
•The same algorithm is applicable for different data types. The data type is specified at
runtime.
•Using generic programming we can design a function or a class which can work with
variety of data types.
• One general code can be designed and used for different data types.
Template Function
Function Templates -We write a generic function that can be used for different data types.
Examples of function templates are sort( ), max( ), min( ), printArray( ).
int main() {
addNumbers(5, 6);
return 0;
}
Template Function
• Like function templates, you can also create class templates for generic class operations.
• Sometimes, you 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.
• This will unnecessarily make your code base and will be hard to maintain, as a change is one
• However, class templates make it easy to reuse the same code for all data types.
Overloading Function Template
Function overloading is polymorphism. Here, we can define multiple functions with same name and working
with different types of parameters.
You may overload a function template either by a non-template function or by another function template.
}
Overloading Function Template
Function Overloading Function Template
1) This feature comes under polymorphism. 1) This feature comes under generic programming.
2) Multiple functions are defined with same name 2) Only one function is defined with generic data
for different operations. type, to perform particular task.
3) Function parameters are specified as C++ data 3) Function parameters can be mixture of template
types. types and C++ types.
4) Overloaded functions can have different number 4) Since one function template is defined, number of
of parameters. parameters will remain same, while calling the
function.
5) Each overloaded function can have its own logic 5) Since there is one template function, same code
and code. works for various calls.
6) Overloaded functions can be called for specific 6) Function template can be used for any compatible
data types, for which functions are defined. data types.
Template class
How to declare a class template?
Class templates like function templates, class templates are useful when a class
defines something that is independent of the data type. Can be useful for classes
like LinkedList, BinaryTree, Stack, Queue, Array, etc.
int main()
{
#include<iostream> Calculator<int> Calc1(25, 12);
using namespace std; Calculator<float> Calc2(13.6, 5.9);
template <class Temp>
class Calculator cout << "Integer results for 25 and 12:" << endl;
{ Calc1.show();
private:
Temp n1, n2;
cout << endl << "Float results for 13.6 and 5.9:"
public: << endl;
Calculator(Temp num1, Temp num2) Calc2.show();
{
n1 = num1; return 0;
n2 = num2; }
}
To create a class template object, you need to define the data type inside a < > when creation.
className<dataType> classObject;
For example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
Class Template and Nontype Parameters
• Class templates are used when we need to perform similar operations on group of data items.
• The functions and data members of the class can either work with template type or mixed data types.
Template<Class TypeName>
class Name
//Data members
//Functions
}
Class Template with Multiple Parameters
#include <iostream>
using namespace std;
template<class T1, class T2>
class Tech output:
{ The values of x and y: 5 and 2.3
T1 x;
T2 y;
public:
Tech(T1 a,T2 b)
{
x = a;
y = b;
}
void print()
{
cout << "The values of x and y: " << x<<" and "<<y<<endl;
}
};
int main()
{
Tech<int, float> data(5,2.3);
data.print();
return 0;
}
Template and Friend Generic Functions
● Introduction
When writing C++, there are a couple common situations where you may want to create a friend function,
such as implementing operator<<. These are straightforward to write for non-template classes, but templates
throw a real wrench in the works here. In C++, there are a few different ways to set up template classes with
friend functions. Each behaves in a subtly different way, which causes all sorts of confusion .We will examine
the possible approaches to this, but first.
● Some terminology
Template instantiation: A specific instance of a templated item; for example, if we have a templated
class A, A<int> is a specific instantiation of A.
Non-member function: A function that is not a member of a class. We will examine these in the context of
friend functions in this article.
Template and Friend Generic Functions (Approach#1)
template<class T>
class A
{
public:
A(T a = 0): m_a(a) {}
template<class U>
friend A<U> foo(A<U>& a);
private:
T m_a;
};