0% found this document useful (0 votes)
69 views34 pages

Oop Unit 5

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)
69 views34 pages

Oop Unit 5

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/ 34

Subject:- Object Oriented Programming

UNIT-V
Exception Handling and Templates

Department of Computer Engineering


Pimpri Chinchwad College of Engineering & Research,
Ravet, Pune

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

● An exception is a problem that arises during the execution of a program

● A C++ exception is a response to an exceptional circumstance that arises while a program is


running

● It is an event which occurs during the execution of a program, that disrupts the normal flow of
programs instructions

● Ex. attempt to divide by zero.


Exception Handling and Templates

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.";

else if(a= =3) }


throw 4.5; //throwing float exception
Output :
}
Character exception caught.
End of program.
Catch All Exception
The above example will caught only three types of exceptions that are integer, character and double. If an exception occur of
long type, no catch block will get execute and abnormal program termination will occur. To avoid this, We can use the catch
statement with three dots as parameter (...) so that it can handle all types of exceptions.

#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.";

else if(a= =2) }


throw 'A'; //throwing character exception
Output :

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.

#include <iostream> class Sample2


using namespace std; {
class Sample1 public:
{ Sample2() {
public: int i =7;
Sample1() cout << "Construct an Object of sample2" << endl;
{ throw i;
cout << "Construct an Object of sample1" << endl; }
} ~Sample2() {
~Sample1() cout << "Destruct an Object of sample2" << endl;
{ }
cout << "Destruct an Object of sample1" << endl; };
} int main() {
try {
}; Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}

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

• In C++ template classes and template function is a means of generic programming.

•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( ).

#include <iostream> int main()


using namespace std; {
cout << myMax<int>(3, 7) << endl;
// One function works for all data types. This would work // Call myMax for int
// even for user defined types if operator '>' is cout << myMax<double>(3.0, 7.0);
overloaded // call myMax for double
template <typename T> cout << myMax<char>('g', 'e') ;
T myMax(T x, T y) // call myMax for char
{ return 0;
return (x > y)? x: y; }
}
/*Sample program for addition of int and float nos.*/
#include <iostream>
using namespace std;
template <typename T>
T addNumbers(T a, T b) {
T result;
result = a + b;
cout<< "the addition of two nos: "<<result<<endl;
return result;
}

int main() {

addNumbers(5, 6);

double num3, num4;


cout << "Enter two double numbers: ";
cin >> num3 >> num4;
cout << "The sum of " << num3 << " and " << num4 << " is: " << addNumbers(num3, num4) << endl;

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

class/function should be performed on all classes/functions.

• 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.

#include <iostream> int main()


using namespace std; {
template<typename T> f( 1, 2 );
void f(T x, T y) f('a','b');
{ return 0;
cout << "Template" << endl; }
}
void f(int w, int z) /* Output:
{ Non-template
cout << "Non-template" << endl; 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?

template <class T>


In the above declaration, T is the
class className
{ template argument which is a
... .. ...
public: placeholder for the data type used.
T var;
T someOperation(T arg); Inside the class body, a member variable
... .. ...
}; var and a member function
someOperation() are both of type T.
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; }
}

void show() /*Output:


{ Integer results for 25 and 12:
cout << "Addition is: " << n1 << "+" << n2 << "=" << addition() << Addition is: 25+12=37
endl;
Subtraction is: 25-12=13
cout << "Subtraction is: " <<n1 << "-" << n2 << "=" << subtraction()
<< endl;
} Float results for 13.6 and 5.9:
Temp addition() { return (n1 + n2); } Addition is: 13.6+5.9=19.5
Subtraction is: 13.6-5.9=7.7 */
Temp subtraction() { return (n1 - n2); }
};
Template class

How to create a class template object?

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

template<class T> 15 A<T> foo(A<T>& a)


{
return a;
}
Template and Friend Generic Functions (Approach#2)
1 template<class T>
2 class A
3{
4 public:
5 A(T a = 0): m_a(a) {}
6
7 friend A operator+(const A& lhs, const A& rhs)
8{
9 return lhs.m_a + rhs.m_a;
10 }
11
12 private:
13 T m_a;
14 };
15
16 int main()
17 {
18 A<int> a(5);
19 A<int> b(7);
20 int i = 4;
21
22 a + b; // Succeeds
23 i + a; // Also succeeds
24 return 0;
25 }
Template and Friend Generic Functions (Approach#3)
1 template<class T>
2 class A;
3
4 template<class T>
5 A<T> foo(A<T>& a);
6
7 template<class T>
8 class A
9{
10 public:
11 A(T a = 0): m_a(a) {}
12
13 friend A foo<T>(A& a);
14
15 private:
16 T m_a;
17 };
18
19 template<class T>
20 A<T> foo(A<T>& a)
21 {
22 return a;
23 }
The type name and export keywords
■ In a template declaration, typename can be used as an alternative to class to declare type template
parameters and template parameters
■ Inside a declaration or a definition of a template, typename can be used to declare that a dependent
qualified name is a type.

template <class T> class Demonstration


{
public: void method()
{
T::A *aObj;
};
typename T::A* a6; it instructs the compiler to treat the subsequent statement as a declaration.

You might also like