0% found this document useful (0 votes)
54 views

Unit 4

Uploaded by

kadama.soham
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)
54 views

Unit 4

Uploaded by

kadama.soham
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/ 40

gramming and Exception Handling in C++

iempiate Pr
HNdng "Y"V" 159
.

Chapter 4

File Handling, Template


Progran
rOgramming and Exception Handling
in C++

File Handling in C++


41

42
Template Programming
4.3 Exception Handling in C++
Questions

41 FILE HANDLING IN C++:


41.1 Introduction:
The present day computers are used to store a very large
amount of data. The amount
of data stored in railway bookings, in bank transactions of large banks, in computers
managing mobile communications and their billing is very huge,
which may aggregate
as floppy disk or hard disk,
to billions of
bytes. All this data is stored in the devices such
compact disc. The data is stored in these devices using the
concept of files. A file is a
collection of related data stored in a particular area on the
disk. The story does noi end
With storage. The data has to be retrieved fast. In
case of a travel booking agency, the
response to his inquires. In such cases, the data should be
tomer needs quick access data randomly, are called
aCCessible randomly. Such files, from where you can
access files. The other form of storing files is
sequential files in which data is
Om file, if you wish to find some data, you have to start
dEquentially. In a sequential
oking from
the beginning till you find your data.
4.1.2
File Streams:
In C++,
classes for file stream operations are:
) ifstream
i) ofstream
(ii) fstream
These cla These classes, designed to manage the disk
files, ses are derived from iostream. include in any program that uses files.
in fstream and therefore must
are deck
ared
160 Vipul's" Object Oriented
Programming
with
-ios th
C
istream ostream streambuf

ifstream iostream ofstream filebuf


fstreamj

fstreambase
4.1.3 Opening and Closing a File:
For opening a file, we must create file
a stream and then link it to the filenan
class to be used depends upon the purpose,
that is, whether we want to
file or write data to it. A file can
be opened in two ways: read data
from
i) Using constructor
of the class
(ii) Using open () function
of the class
(i) Opening files
using constructor:
The first operation generally performed
This procedure is called as to on file object is to associate
'open a file'. An open file is represented it to a prooran
real ke
by a stream object and any within a
input or output operation performed
will be applied to the physical
file associated to it.
on this stream obiet
In order to open a file
with a stream object, we use its constructor
ofstream fwrite ("filename. function as:
ofstream: Stream class to
txt");
write on filee
fwrite: name of the ofstream
object.
It opens file 'filename.txt' in
one. writing mode if it is present,
otherwise it creates a new
For example,
Program to demonstrate
Opening a file using Constructor
#include<iostream.h> Function:
#include<conio.h>
#include<fstream.h>
void main()

clrscr);
ofstream fwrite("one.txt");
fwrite«<"This
is the first
fwrite.close); line in the file";
getch);

It opens the file


'one.txt', if it
and then Writes "This exists; otherwise
is the first line it creates a new file name one.
in the file' in
the file.
g aand Exception andling in C++ 161
Programming
ProgBra
Template
ndins usir open 0 function
function:
files using
sing opena le with a stream object, we use its open function as:
ing
Opening
der to
order
rite
h .open
ofstream
fwri("filename.txt");
open taken one argument, "filename.txt", (filename). If this file exits, it
furit function
has
has
mode, oti
ent)writingmode, otherwise it creates a new one.
demonstrate Opening a file using open0 Function:
Vgramto tream.h>
incude<10S
#include<conio.h>
#include<fstream. h>
mainC0
void
clrscrO;
data[80];
char
ifstream fread;
fread.open ("one. txt
") ;
whileC!fread.eof())

fread.getline(data, 80);
cout<<data<<end1;

fread.close();
getch);

Output:
in the file
This is the first line from data from files
ifstream is used to read class.
fstream mode and data will be
fread: is the object of open the file in read
If 'one.txt file exists, then
open () will
read and printed on the screen
line by line.
lii) Closing a file:
output operations on a file, we have to
When we are finished with
our input and
dlose it so that its resources become
available again. For
function close() of stream classes.
10 close a file, we have to
call the member
examples, the call to close() method:
CkImple, in the above two

fwrite.close()
associated
fread.close() parameter, and it flushes the
function does not take any
f ember
Duifers first and then closes the file.
414 File
Opening Modes: and the function open () to create
We have
used ifstream and ofstream constructors case, we used only one argument,
the
existing file. In both take two arguments, the second
Pew file
new file
eLl as to open the
is, filename. these functions can function open() is:
argument,
spe
e.However, The general
form of the
nes the file mode.
Obj
bject Oriented
Prograh
162
("filename", mode); ammiry

streamObject.open purpose for which the file is openeed The


specifies the defailt
The mode
mode are: ofstream functions meaning open for .va
iso::out for open
meaning readin for reading
for
ios::in forifstream functions only

File Opening
Modes:
Description
Mode end of file
Mode for appending at the
ios:app file
ios::ate Mode for opening at end of
file
ios::binary Mode for opening as binary
ios::in Open for reading mode
In this mode the open() function fails if file does nat exist
ios:nocreate
ios::noreplace In this mode the open() function fails if file exists
| ios::out Mode for opening the file for writing
ios::trunk Mode for deleting the conternts of the file if it exists

Program to demonstrate ios:: append mode:


Program to demonstrate ios:: append mode
#include<iostream.h>
#include<conio.h>
#include<fstream. h>
void main()

clrscrO:
char data[80];
ofstream fwrite("Student.txt",ios: :app);
fwrite<<"Rol1No\t Name\t\t Percentage"<<end1;
fwrite<"A101\t Janvi Ahuja\t 79.5%"<<endl;
fwrite«<"A102\t Sunil Sharma\t
62.6%"<<end1;
fwrite««"A103\t Rakesh
Sagar\t 76.78%"<<endl;
fwrite.close():
ifstream fread("Student.txt");
while(fread)

fread.getline(data,80)
cout<data«<endl
fread.close
getch();
();
Propr nming and Excepti Handling in C++
V"Y"V 163
dienplate

Duput Name
Percentage
Ahuja 89.95%
NO.
Sagar 72.56%
Lae
Rinku 56.78%
tap
Rudra Pra

Name
Percentage
No. 79.5%
huja
oll Janvi
Sharma 62.6%
Sunil 76.78%
RakeshSagar
Checking End of
File:
end-of-file necessary for preventing any further attempt
Detection e end-of-file condition
of the
is
Dete
data from
the file.
oad whi leCfread)

object, such as fread, returns a value of 0 if any error occurs in the file
ifstream the while loop terminates when
on
Operation
including the end-of-file condition. Thus,
a value of 0 on
reaching the end-of-file condition.
freadIreturns
another approach to detect end-of-file condition.
There, is
while!fread.eof (0) end-of-file
class. It returns a non-zero value if the
function of ios
nf ) is a member a zero, otherwise. Therefore, the
above statement
EOF) Condition is encountered, and program.
reaching the end of file, as illustrated in the above
leminates the program on
and reading) to file in the same
Output (writing
Program to demonstrate Input and
program:
includeciostream.h>
Fincludecconio.h>
Fincludecfstream.h>
void main()

clrscrO;
char data[80];
ofstream fwrite("Student.txt");
Percentage"<<end1;
fwrite«"Ro1No\t Name\t\t 89.95%"<<endl;
fwritee"A101\t Sagar Ahuja\t
72.56%"<<endl;
Twrite«"A102\t Rinku Lae\t 56.78%"<<end1;
write«"A103\t Rudra Pratap\t
fwrite.close();
ifstream fread ("Student.txt")i
whileCfread)

fread.getline(data,80);
Coutecdata<<end1;

fread.close()
getch);
Dutput.
vipul's Object orlented Programming
with

Ro11 No. Name Percentage


A101 Sagar Ahuja 89.95%
A102 Rinku Laae 72.56%
A103 Rudra Pratap 56.78%
4.1.6 Random Access in File:
a file, which 1s determined by the ofe r (nu
points to a position in is opened in the umb
pointer
or bytes) from the beginning or from the end. When a file when fil oda e
the file. Similarly, the
beginning of
s beginning of file because opening in Pene
positioned at the
ne pointer is again at the 1s poSitloned at the bee
mode
the pointer
res the existing
append
contents
mode
of the file,
(iso:app)
so
the pointer is at the end of file ready
contents remain intact.
read,ning
to add
data. In the append mode the existing
onal and output pointer are associated with evem
WO pointers, i.e. input pointèr
input pointer which is used for reading the file from a particular location is callhe
for writing in the file 1s called put. pointer
Pnter. The output pointer which is toused a location in the file are
ne functions used to shift the pointer
Function Header file Description
seekg() <ifstream.h> It moves the file get pointer to.location specifiedh
its arguments. Used for reading.
seekp0 <ofstream.h> It moves the file put pointer to specified location
its arguments. Used for writing.
tellg) <ifstream.h> It returns the current position of the get pointer
tellp0 <ofstream.h> It returns the current position of put pointer.
seekg() and seekp() functions have two arguments. "The
first is an integer number
which specifies the offset and the second specifies
the reference position from where the
offset is measured, that is from file rea
beginning,
from file end. The codes for the three references from the current position of pointer or
are:
seekg(int ofset, ref-pos);
seekp(int offset, ref pos);
Code for reference
ios::beg Description
From the beginning
ios::cur of file
From the current
ios::end position of file
From the end of file
Seekg) call
Description
fread.seekg (0, ios::beg);
Go to start
fread.seekg (0, ios:cur);
Stay at the current
fread.seekg (0, ios::end); position
Go to the
end of file
Programm Exception Handling in
165
Template
ndling,
ios::b
beg); Move to (m + 1)th byte in the file
2ad.seekg(m,
ios::Cur Go forward by mbytes from the current position
fread.seek8(m,
ios::cur); Go backward by m bytes from the current position
eekg (m,
fread.seek
2ad.seekg(m,.ios::beg); Go backward by m bytes from the current positiorn
ios::end): Go backward by m bytes from the end
fread.seekg(-m,
10s::beg)
) Go to beginning of file
fwrite.seekp(0,
10S::cur) Stay at the current position
fwrite.seekp(0,
fwrite.seekp(o, ios::end) Go to the end of file
fwrite.seekp(n, ios:beg) Move forward by n bytes from the beginning
fwrite.seekp(n, ios::cur) Move forward by n bytes from the current position

fwrite.seekp(-n, ios:end) Move back by n bytes from the end of file


an integer which indicates the current position
The functions tellp() and tellg) return
for writing
and reading respectively.
functions:
Program to demonstrate seekg) and tellg)
#include<conio.h>
#incTude<fstream.h>
void main(0

clrscr:
char freadwrite("A1phabets.txt",ios::inlios: :out)
C;
fstream
get stored in the file
// abc upto z wi11
forCchar i='a';i<='z';i++)
freadwrite«<i;
|freadwrite.seekg(ios::beg)
;

freadwrite.get(c); "<<freadwrite.tell9)«<" : "<<c;


position
cout«<"\n Character at
cout<<"\n\n";
whileCfreadwrite)

freadwrite.get(c)
cout<<C;
1331
freadwrite.seekg(5, ios::beg); position:
is at
freadwrite.get(c) incrementing the five positions
after
cout«"\n Cursor "<<freadwrite.tel1g()<<" "ec: :

"freadwrite. tel1g0; at position


cout<e"\n Character "F at 6th position
freadwrite<<"F"; //inserting of the file will be:s
now the contents
ITAfter insertion, freadwrite.seekg(ios: :beg);
cout<<"\n\n";
while(freadwrite)
Vipuls ODject Oriented
Orien
Progra
amming
166 cirscr
; vth
freadwrite. get(c) student
cout<<c; strean
freadwr
freadwrite.close0; cautsce
getchO;

freadw
Output
Character at position 1 : a is at position: 6
five positions
Cursor after incrementing the
Character at position 6:f position
Contents after inserting F at 6th
abcdefFhijklmnopqrstuvwxyz2
Random Access: freadr
invo
in a file which may involve insertion
Often it is required to update the data
coutss
a file. cOut
deletion of data in the middle of file or at ends of hile(frea
These actions require the file pointers to move
articular lo
tO a particular
location
that
corresponds to the object under consideration. st.sn
A better solution is to have random access file. In such a file each obieet occup
specified number of bytes. If each object is allocated 'm bytes and then to pies
int n
object, we have to have an offset of (n - 1)*m bytes. We can easily reach the requiredl nth COuts :
Couts
object.
int
Program to demonstrate Random Access: cinbs

#include<iostream.h> cin.get(
#include<conio.h> int
#include<fstream.h> ifCf
class student frea
{
frea
char name [30]; Cout
int age; st.g
float percent; cin
public: frea
void getdata () frea
cOu
cout<<end1<<"Enter name: "; COU
cin>>name; thile(f
cout<end1<<"Enter age: ";
cin>>age;
st
cout<<endl<<"Enter percentage:
";
cin>>percent;
fre
void showdata() 9et

cout<<endl<<name; tput:
cout<<"\t\t"<« age; Current
cout«"\t\t"<<percent; Narc
Sanjeel
Rakesh
void main() Sanar
clrscrO; 167
ent st: dwriteC"Student.txt",
fstreaite.seekgCO,ios: :beg); iosate |
ios::in | ios::out);
"Curre
rent contents of
Cout<s rite.read((char*)&s
nhile(freadwrite. file":
st.showdata(); (st)))
freadwrite.clear()D;
endl<<"Enter details for one
more student";
st.getdata();
char C
cin.get(c);
freadwrite.write(Cchar*)&st, sizeof (st)):
freadwrite.seekg(O;
<<endl<<"After ition of one more student";
end1<<"Name
cout<<en \t\t Age \t\t Percentage";:
(freadwrite. read(C
Cchar*)&st, sizeof(st)))

st.showdata();

int n freadwrite.tellg()/ sizeof(st):


<"Total
cout<<endl<<" no. of student record: "<<n;
couteeendl<<"Enter student number to be updated: "
int num
cin>>num;
cin.get(c) ;
int 1=(num-1) sizeof(st);
*

ifCfreadwrite.eofC0
freadwrite.clear)
freadwrite.seekp(1);
cout<cendl««"Enter new values for the student"
;

st.getdata();
cin.get(c);
freadwrite.write((char*)&st, sizeof (st)) «<flush;
freadwrite.seekg(0);
Cout<<endl<<"After updation contents are"
Percentage";
cout<<end1<<"Name \t\t Age \t\t
sizeor(St)
le(freadwrite. read ((char ) &st,
st.showdata();

freadwrite.closeO;
getch ();

Output
Lurrent
contents of file
Name Percentage
Age
Sanjeela
Rakesh
33 78
34 82
Sagar
22 67
Vipul's Object Orientedd Programming
Propr
168 with
c
Enter details for one more student
Enter name: Kashyap
Enter age: 19
Enter percentage: 89
After addition of one more student
Name Age Percentage
Sanjeela 33 78
Rakesh 34 82
Sagar 22 67
Kashyap 19 89
Total no. of student record: 4
Enter student number to be updated: 4
Enter new values for the student
Enter name: Kashyap
Enter age: 20
Enter percentage: 80
After updation contents are
Name Age Percentage
Sanjeela 33 78
Rakesh 34 82
Sagar 22 67
Kashyap 20 80
4.1.7Command Line Arguments:
Command line arguments are optional string argumernts
program upon execution. These arguments that a user can give to
program, and the program can
are passed by the operating
system to the
a
use them as input.
Programs are normally run by invoking
a program, you can them by name. On the command
simply type in its name. For line, to run
CMDLARG' that is located example, to run the executable file
in C:\TC\BIN on a windows
C:1TC\BIN\CMDLARG machine, we have to type:
In order to pass command
line arguments to CMDLARG,
command line arguments we simply list the
after the executable name.
C:\TC\BIN\CMDLARG
one.txt
Now when CMDLARG
argument. A program is executed, one.txt
can have multiple will be provided
command as a command ime
C:\TC\BIN\CMDLARG line arguments,
one.txt student.txt separated by space
Program to demonstrate
Command Line
#include<iostream.h> Arguments:
#include<conio.h>
#include<fstream.h>
void main (int argc,
char *argv[])
char C;
int wc=l;
ifstream fwordcnt
(argv[1]);
cout<endl«<"Contents
while(fwordcnt) of the
file are\n"
169
fwordcnt.get(c);
ifCC==" ')
WC++
cOut<<C;

<cend1««"The words in the file are <<WC;

getchO;

Output: cmdTarg one.txt


:TC\TC\BIN> cmdlarg
Contents of
the file are
th
the
he first line in the file
This is the file are:8
words in
Working with Binary Mode:
The
41.8
lo ctream classes support a number of member functions for performing the
The leoutput oerations on files.
inputand
We are going to
use the following two pairs:
a
put).and get(): Are designed for handling single character a time.
e arrite) and read): Are designed for handling write and read blocks ofbinary data.
AgGDut) and get0: The function put() is used to write a single character to the
associated stream. The function get() reads a single character from the associated
stream.
Program to demonstrate get() and put() functions:
#include<iostream.h>
oTE #include<conio.h>
#include<fstream. h>
void main

clrscr); ios::out) ;

fstream freadwri te ("EngA1pha.txt",


ios: : in|

for(char c='A';c<='Z'; c++)


freadwrite.put(c)
freadwrite. seekg(0);
char i;
whileCfreadwrite)

freadwrite.get(i);
cout<i :

freadwrite.close);
getch)
Output:
ABCDEFGHIJKLMNO
1NOPQRSTUVWXYZ
Vipul's Object Oriented Programming
170
with
C
mentioned earlier, write) arnd read() function
(11) write() and read(): As ndles
that we can write and read
block of binary data, hence it is quite natural objecsa
the entire structure (i
directly from the disk files. The functions handle the
members) of an object as a single unit. data
|Program to demonstrate write() and read) functions used for reading andwriling
g and
class objects:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
class student

char name [30]:


int age
float percent;
public:
void getdata()

Cout<<endl<<"Enter name:"
cin>>name;
cout<<end1<<"Enter age: ":
cin>>age;
cout<<end1«<"Enter percentage: ";
cin>>percent;

void showdata()

cout<<end1<<name;
cout<"\t\t"<< age;
cout<<"\t\t"<<percent;

void main)

clrscr:
student s[3];
fstream freadwrite("Student.txt", ios::in |
ios: :out);
cout<cend1<<"Enter details for three
students";
forCint i=0;i<3; i++)
s[il.getdata ();
freadwrite.write((char*)&s[il, sizeof(s
[i]));
freadwrite.seekg(0);
cout<cend1<<"Name
\t\t Age \t\t Percentage":
for(i=0;i<3; i++)

freadwrite.read((char*)&s
[i], sizeof(s[i]));
si].showdata():
getch)
Programming and EXCeption Handling in C+
Pro
emplate
late
171
Hanaung
file

Oulput:
details for three
student
Ente name Sanjeela
Enter
age: 33
and Enter percentage: 78
Enter name: Rakesh
Enter
age: 34
Enter percentage: 82
Enter
name: Sagar
Enter
22
Enter age:
percentage: 67
Enter Age Percentage
Name
Sanjeela 33 78
Rakesh 34 82
67
Sagar 22
The function writel copies a class object from memory byte by byte with no
conversion. The length of the object is obtained using the sizeof operator
4.1.9 Error Handling:
The stream I/O operations are also prone to errors which may be due to programmer
r due to constraint of the hardware such as insufficient memory or due to user. The
errors may be of following types:
oUsing a wrong file name
Attempt to read a non-existing file
Attempt to write on a read-only file
Attempt to open a read-only file for modifications/writing
Attempt to open a new file with the name of a already existing file
Attempt to read the file when the pointer is set at the end of file
Hardware problem
Hard-disk space insufficient
Function Description
eof) Returns true if end-of-file is encountered, otherwise returns false
fail() Returns true when an input or output operation has failed
bad() Returns true if error has occurred, otherwise returns false
clear) Clears error states
returns false
good) Keturns true when no error has OCcurred, otherwise
Tdstate()
Returns the stream state data
|

sram to demonstrate Error Handling:


#includeciostream.h>
int main)
Programming and Exception Handling in C++
Tem late Y"" 173
Handling,
Fie after inpu
tream State
The
cin.bad = 0
cin.good = 0
cin.
fail= 2
cin.eof= 0 tion of function lear()
applicati
After
cin.bad = 0
cin.good = 1
cin.fai1= 0
cin.eof =0

4.2
TEMPLATE PROGRAMMING:
4.2.1
Introduction:
of the nmain advantages of object-oriented programming.
One
Code reusability is one once and call it any
way to achieve
code reusability is to write and compile the code
in a program. for Example, a large ( ) function defined to find largest
number of times
can be called any number of times with different integer
number among two integers cannot be
provides a way to re-use an object code. However, this code
values. This to write
data types such as float or double. Thus, the programmer has
called for other of overloaded
for different data types (as in the case
the same code repeatedly operation is to be performed on different
where the same
functions). In such situations,
data types, templates can
be used. operates on
generic function or a generic class that
Templates enable to define a furnction or a class for each type.
creating a separate
various data types, instead of parameterized types. The C++ template
as generics or the definition of a
lemplates are also known as a parameter in
allows a generic type to be passed different types of data. Such approach of
Cnanism can work with of using a
TUnction or a class so that they programming. The main advantage
as generic flexibility.
ng programs is known code size and also increases code and
plate is that it reduces the
source
are known as function templates
functions, they
en templates are used withthey are known as class template
classes,
En they are used with
4.2.2 situation when the same among code has
Function Template: be a
overloaded functions, there may For example, to find largest
to
e writing
for different types of data.
separate functions have to be
created
ritten repeatedly numbers, two
and two floating -point third
ea5s
for each
the result is stored in the class.
of the data type.
are added and used to add two objects of
a
Statement, two variables
riab +operator cannot be directly
For Owever, the
Examnl
ror Example,
nt large (int x, int y)

if (x> y)
return x;
Vipul's Object Oriente
Programming

174

else
return y;
x, float y)
float large (float
if (x> y
return X

else
return yi
differennt
functions large () with data types
example, two overloaded numbers of oth
In this largest among two atatypessudh
defined. If the need arises to find
functions have to be derined.
1hs makes thoP
the
more
ong double, etc., then maintain. In such a situation, function templates cagtan
used.
lengthy and difficult to function, detines a group. a
A function template, also
known as a generic on different data tvn
family

functionality but operating ypes.


functions having the same
one function signature needs to be define defineWhi
using function templates,
only
generates the required functions for handling the indi,nd
ndividual
daa
t
compiler automatically
types.
Defining a Function Template: PL

templates is similar to the detinition or ordinary functions.kno The


heonli
rel
The definition of A >
statement < template < class and is 1OWn&
different is that it is prefixed by the
he
declared. Whn
that a template is being
template statement. It informs the compiler a
defined, it does not actually define function rather it provides a bluepte
template is
The compiler uses this
bluepri
skeleton for generating many functions.
or a syntactical functions when it is requir h
new member of the family of
to automatically generate a

first.
Syntax:
template <class A> 7/ template statement returntype
function Name (Parameter-list)

// function body

Where,
template is: C++ keyword 50 9 919/1.2rnatoat bobiea
class is: C++ keyword
A: generic or arbitrary type-a type that has not yet been specified but ca be
one
a
the built-in data types or a user-defined data types.
function Name is: Name of the function
parameter list: list of arguments of type A or any other built-in data YPe
return-type: return type of the function. paramet
The letter 'A' in template definition is called template argument orype" is
t

is placeholder name for the data type used by


a
t
the function. No
keyword and hence, any valid identifier can also
be used.
ramming and Exception Handling in Ct+
emplatePr
175
Hanaing
Statement must be specified in both the declaration
e Template and definition of the
template.
function
Instance,
<ClassAs //function temp late prototype
For
template y);
A *, A
1arge
A
lassA> nction template definition
template
if (x> y)
return x;
else
return Yi

Templates:
Calling Function
er defining the fu
ter
function template, the next step is to call it in another function,
main (0. Whhen the function template is called with actual data type, the
eda Such as, ingenerates a specific version of the
vidud SUr
compile function template for that data type. A
function generated from a function template is known as a template function and the
known as function template instantiation. The definition created from
templateinstantiation is called specialization.
ns.Ihe When the function template is called, the data type 'A' is dynamically determined by
iskno
the compiler according to the parameter passed and replaced with actual data type. For
Ted.
red.
iEample,consider the function template large () created earlier. When the parameters of
a biype int are passed, the compiler generates large () function compatible for int data type
Is blaand if the parameters of type float are passed,
t 15
it generates the function compatible for
foat data type and so on.
Program to demonstrate calling a Function Template:
#include<iostream.h>
er-lis) #includecconio.h>
template <class A>
A sumCA x, A y)

return X+Yi

void main)
an et clrscr)
int a,b;
COut«<"\nEnter two integers:"
cin>>a>>b;
float f1, f2;
Cout<<"\n\nEnter two float values:"i
cin>>fl>>f2;
uT"\n\nSum of two integers:"<<sum(a,b)
Out"\n\nSum of two floats:"<<sum (f1, TZ)
getch)
Vipul'sM Object Oriented
Proarmming
176
ith
vith

Output:
Enter two integers:
12
23
Enter two float values:
12.78
34.56
Sum of two integers: 35
Sum of two floats: 47.34
template large ( ) 1s called and called in nain()with
In this example, a functioncompiler automatically generates appron)
opriate
win

int and float. Note that the


functions for data type int and float using the function plate.
template. This
This is
te
called
ten
jn te
instantiation.
be instantiated by expliciH. speci
However, a function template can also
data type while calling the function
template. This is known as explicit instan ation.
For Example:
cout << large <int> (4,2); er
«"\n"
cout << large <float> (22.67, 111.8):
Function Templates with Multiple Parameters:
bath of
The function template large () defined above accepts two parameters,
'A'. Thus, the function template cannot be called with two parameters of
different

types.
This problem can be resolved by specifying a comma-separated list of more thane
generic data type in the template statement.
Syntax: ha

template <classA, classB, ----, classNs


returntype functionName (arguments of type A,B,---N)

// function body

Program to demonstrate function Template with Multiple Parameters:


#include<iostream.h>
#include<conio.h>

template <class A, class B>


A largeA x, B y)

if(xoy)
return X;
else
return Y;

void main()

clrscr();
int n=10;
empla# Programming and Exception Handling in C++
HannnB
f-22.67; 177
e float
cout"\n\nLarg Numbe (22.67,10): "<<large(f,n);
m=50;
int "\n\nLargest nber (22.67,50):"<<1arge(f,
cout<< m) ;
getch);

Output:
tNumber (22.67, 22.67
10):
Largest Nunm er (22.67, 50): 50
argest
ever, it can also be instantiated by explicitly specifying the types
float» 0,5.6); between <>:
arge int,
Targe
<float, double> (6.5,21015.67345612);
Function Templates
Overloading
PnPyerenever a fufunction template is called with actual data type, the compiler generates
Whection for that data type. That is, a function template
new fun overloads itse
a
atically by zenerating a new function whenever needed. However, a function
automaticall
emplate can be overloaded either
by:
@ Another function template, or
(i) An ordinary
function.
Overloading By Another Function Template:
function template can be overloaded by another function template having the same
A

name, however, with difterernt number of parameters. Note that in the case
of simple
functions, the overloaded functions can have different type as well as number of
Darameters. However, in the case of function templates, the overloaded functions can
have only different number of parameters as the template
can already handle different
data types.
Program to Demonstrate Function Template Overloading by another Function|
Template:
#include<iostream.h>
#includecconio.h>

template <class A>


A
large(A x, A y)

if(x>y)
return X;
else
return y;

template <class A>


A
large(A x, A y, A z)

if(large(x,y)>z)
return large(x, y);
else
return z;
Vipul's
178
er Object Oriented
Programmi.

void main()

clrscr) (4,2):"<<large(4,2);
Cout<"\n\nLargest Number:
Number(4, 10, 5): "<<large(4, 10, 5);
Number (12.34,11.98) "<<large (12.34,11.98)
cout"\n\nLargest
coute"\n\nLargest Ra
coute"\n\nLargest Number (22.67, 50.89, 111.78): <large (22.67,50,89,111.78);
getch)

Output:
Largest Number: (4,2):4
Largest Number(4, 10,5) :10
Largest Number (12.34,11.98) 12.34
Largest Number (22.67, 50.89,111.78):111.78
(2) Overloading by an Ordinary Function:
Sometimes there may be a situation when a function template may not work w
with
certain type of data. For Example, consider the function template large () defined
in
above example. When this function is called with string values, the compiler generrates
an error message.
In such a situation, the function template can be overloaded by an ordinary
ction
with the same name but accepting string data types as parameters. Overloading of
a
function template by an ordinary function is known as explicit specialization
or explicit
overloading.
Program to demonstrate Function templates overloading by an Ordinary Function:
include<iostream.h>
#include<conio.h>
nelude<string.h>
ib.57
template <class A
A large&A x, A y)

if(x>y)
return X;
else
return Y:

char* 1arge(char ts1, char*s2)

if(strcmp(s1, s2)>0)
return s1;
else
return s2;
void main()

clrscr);
cout"\n\nLargest Number:
(4,2): «<large(4,2)
Excep Handling in C+
ogramming and
Templa
VY"Y 179
Nin (12.34,11.98): <<large(12.34,11.98);
Hanalli \nLargest
ecOut<n
n\nLa st String(Sanjeela, Sagar): "<<large("Sanjeela", "Sagar");
cout
getchO;

Output Number (4. 2):


4
Largest Number (12.34, 11.98): 12.34
Large:
(Sanje
njeela, Sagar): Sanjeela
Largest tringFunction'Templates
4pplicability
icability of can be used wherever the same set of operations has to be
emplates
functio
The with
erent data types. The mathematical and logical operations such as
differen
erformed wit
subtraction comparison, etc. are few examples where function templates can
riorubtraction,
addition,
Moreover, operati
Aditionreover, operations on a single dimensional arrays such as sorting, searching
use on 2-Dimensional arrays (matrices) such as addition, multiplication
he seonerations
be opera
and
also.
implemented using function templates.
anoar Templates:
Sort Using Function
templates
Sorting using Function
/
#includeiostream. h>
#include<conio. h>

templatecclass A>

void sort(int n, A arr[])

int i, J
A t;
for(i=0;i<n-1;i++)

for(j=i+1;j«n;j++
if(arr[i]>arr [j])

t-arr[i];
arr[i]-arr[j]:
arrCil=t

template<class A>>
void show(int
{
n, A arr)

int i;
cout&"\n Array
after
for(i=0;i<n;i++) sorting\n"i
Cout&earrli]<e"\t";
void
main)
180
76};
clrscrOD: 6,4,5,3,2, 1}; 45.8, 67.9, 9.
nl]={8, 7,9, 2.89,
int f[]= {6.2, 3.7, 'q', 'c };
floatc[]=['s', 'a', 'h',
char
n) ;
sort (9, f);
sort (6,c);
sort(5,n);
show(9,
show(6, f);
show(5, c);
getch()

Output: 7 8 9
sorting 6
Array after
3
2
67.900002
Array after sorting 6.2
45.799999
3.7 9.76
2.89

Array after sorting


C h Templates:
Restrictions of Using Function C+4 they
most useful features of C++, #.
ave
Though templates are one of the
functions having different functionalit
nctionalities t
havecette
canno
restrictions. The overloaded template
template, as the function must
mis periorm
replaced with a single function types.
te
all the data
same general actions for
For Instance,
/Calculates area of
int area (int S)
//a square
return (S*S);

int area (int 1, int b)


//Calcu1ates area
return (1 *b); 7/of a rectangle
}
int area (float radius) //Calcu1ates area
//of a Circle
return (3.14* radius * radius);

All these overloaded functions have ifet


different functionalities. Note thatd
atingt*
actions are performed inside the body of each function as the formula forcalculeu
area is different for different geometrical
shapes. Hence, these funcuo
replaced with a single function template.
4.2.3 Class Template:
mplate
Like function templates,
class templates
can also be created in Ctt
also known as a generic class, defines having
class definition but handling different a group or a family of clas templates0
type of data. While usin5 class
oramming and Exception Handling in C++
Template 181

HanonnE seds to be created and the compiler automatically


nee
definit
ition generates the
ae def
Classclasses for
handling the individual data types.
one ed template 1sed in those situations where two or more classes have the same
guired,
lass but but handle different data types.
Adetinition mstrate the Need of class templates:
demonstrat
class
mto
stream.h>
Poglude<iost
Tude<Conio..h>
inc
sinc
elass
ca
X,Y
int
public:
void get(
<<"\nEnter two numbers:";
Cout<"
cin>>x>>y;

int sum)
return X+y;

subCO
int
return X-y;
mul(O
int
return x*y;

int div)

return x/y;

void display)
Y="<<y;
cout«<"\n X="<<x <<"\t
COut<<"\n****************k*\n":
"<sum();
+ "<< y<<
cout<<"\n" <« x
"
<< "sub);
cout<<"\n" << x <<"- "<< y<< "<<mul);
"
=
" * "<< y<<
Cout<<"|\n" << x << "<div);
"/ "<< y<<
"

Cout<<"\n" << x <<

void mainC0

clrscr)
cal c
C.get ();
c.display
getch :
():
Vipul's Object Oriented
182 Prograr
sarnmine

itho
Output:
Enter two numbers:
12
11

X-12 Y=11
t *** ****** *******
12 + 11 = 23
12- 11 = 1
= 132
12* 11
12/ 11= 1-
In this example, a class 'cal' is defined to sum, subtract, multiply
ultiply a
numbers of type int. If the need arises to perform the same operations and
#h
on de
thenumbers
type float, double, long, etc. then the programmer has to
ate separatmbe
create separate
nandledifferent type of data. This problem can be resolved by defining a claseses dasses
Defining a Class Template: classtempl t
A class template must be defined
before creating its objects. The definition
template is similar to an ordinary class, except
it is prefixed by the statement ot adass
template <classA>.
Prooran
TOgram to demonstrate class Template Definition:
// Defining a class
#include<iostream. h> template
#include<conio.h>

template<class A>
class cal
{
A X,Y; .

public:
void getO

cin>>x>>y;
}
A sum()

return X+y;
A sub)

return X-y;
A mul ()

return x*y;
A divO

return x/y;
Handling in C++ 183
nd Exception
Prop
"Template

Handling
Han
display()
e void "\n\nX="<<x
cout<<"\n <"\ <<y;
cout<"\n******** tn";
+"<<
" y<< "
= "<<sum();
<< x <<
cOut<<"\n << X <<
"
" yee "
= "<<sub();
<<"\n" < y<< "
"<<mul);
cout
cOut<<"\\n" << x << "
=

="<<div):
cout<<"\n" < x <<
<<

main)
void
clrscr); integers: "
ca1<int> C; two
wo
cout"\NEnter
.get;
cal<tloat>f; two float: ";
fl
utee"\nEnter
/cout
f.get
/c.display0;
f.displayO;
getch);

Output:
twO
1ntegers:
Enter
33
22
Enter two float:
18.6
11.5

X=33 Y=22
************
#****
55
3322 =

33 22 = 11
3322 = 726
33/ 22 = 1
X=18.6 Y=11.5
******************|
18.6 + 11.5 = 30.1
18.6 11.5 = 7.1
l8.6 213.900009 required classes by
*
11.5 =
create the
next step is to process is known as class
=
18.6/ 11.5 1.617391
defined, the
Dut 3 class template is type parameters. This known as a template
providing the actu type for the template is compiler
template actual generated from a class is created, the
Cass. Wh
class.
Stantiation. A classinstance of a class templatenecessary for handling the actual
yer a specific
Whenever,
and functions variables
8enerates all the
Bject Oriented
progaming,
ProgRtan
184

vistht
For Instance,
cal cint> cl;
cal <float> c2; Multiple Parameters:
with
Class Template templates, class templates can also havo
ave more
than
Like function negenetic
class template statement.
type in the Multiple Pa. tiple Paramete
demonstrate Class Template with da
Program to parameters.
with multple
77 class template
#include<iostream.h>
#include<conio.h>

A, class B»
template<class
mcheck
class
{
A a;
b;
public:
void get)

cin>>a>>b;

void show )

cout<"\nA="<<a <<"\tB="<<b;

void main()

clrscr)
mcheckeint, float>mc1;
mcheckechar, float>mc2;
Cout&<"\nEnter one integer and one float: ";
mcl.getC0:
cout<<"\nErlter one character and one float: ";
mc2.get :
cout<"\n\nobject 1 Data"
Cout<"\n***************",
mc1.show0;
COut<"\n\nObject 2 Data"
Cout«"\n***********tt**"
mc2.show():
getch0:

Output
|Enter one integer and
one float:
12
13.45 1
Prograamming and ception Handling in C+

Handiling
lempiate " 185

nd one loat:
chara
one
nter
5.68 Data
********tt*
ohject
B-13.45
a-12
Data
2
**********
object
**tt B-45.68 oof a Class Template:
Specialisation
ecialisation
AS
Explicit mecialization of a class template can be provided for handling one or two
explic
An cases.
Special
demonstrate Explicit specialization of a class Template:
to de
Program to Specialisa
isation of a Class Templ
Explicit
Ex
#incTude<iostream.h>
#inc1ude<conio. h>

A>
template<class
class abc
A a;
public:
void get)

cin>>a

void show()
cout<<"\nClass Template Called";
Cout<<"\NA="<<a;

Class abc<int>

int a;
public:
void getO

cin>>a

void showC)
Specialization CaTled"i
Out\nExplicit Int
cout<<"\nA="<<a;
186
vipul'sM Object
Oriented rogrammine
void main() w

clrscrC);
abccint>al;
cout<"\nEnter an integer: ";
| al.get C);
cout<<"\nEnter a float: ";
abc<float>a2;
a2.get(;
cout<<"\n\nobject 1 Data";
Cout<<"\n¥** t ttut*tttttt "
al.showO;
Cout<<"\n\n0bject 2 Data";
COut<<"\n**** t tt wtwt*tt ttw";
a2.show);
getch ():

Output:
Enter an integer: 11
Enter a float: 12.34
Object 1 Data
t**t*******
Explicit Int Specialization Called
A-11

Object 2 Data

Class Temp1ate Called


A-12.34
A
In this example, an explicit specialization for int data type
is given for the clasS
template. If a template class className <int> is created, the compiler calls
the
specialised version of the class. For other data types, the class template is called.
Non-Type Class Template Parameters:
A class template can have non-type parameters of built-in data types. However, a lrin
class template carn only have integral data type such as int, char and long as non-type
parameters. These parameters are usually used to specify the array size, or the upper
and lower limits for index values. ome
s
Program to demonstrate non-type class template parameters:
//non type template parameters with class

#incTude<iostream. h>
#include<std1ib.h>
#include<conio.h>

template«class A, int n>


class ncheck
A arr[n]:
olate r8
emplate
Handing,
187
Fle pub1icCO
ncheck
0;i<n;i++)arr arr[ij=i+1;
forCint
(int i)
operator[
r[]
A&
ifCi<0 I| i>=n)

cout<<"\nArray index out of bounds":


exit(1);

return arr[i];

main()
void
clrscr();
ncheck<int, 5> nc;
int Array\n";
rout<e"\n Integer
Ci-0;i<5;i++)
for
nc[iJ=i+1;
for(i-0;i<5;i++)
cout&enc[i]<<"\t";
getchOan
Output:
Integer Array
2 3 4
esz4.3
eist= EXCEPTION HANDLING IN C++:
4.3.1 Introduction:
is the main objective of programmers. However,
Writing error-free programs These errors
for the first time, it usually contains errors.
d
long E Whenever a program is written compile-time errors, logical errors and
three types, namely,
size utare classified mainly into removed
compile-time errors and logical errors can be detected and to
ume errors. The
testing and debugging. However, run time errors
are difticult delete
xnaustive to as exceptions.
rap. The run-time errors are usually referred occurs during the execution of
a program
that
Eption is an unexpected event terminates the program abnormally.
The
the normal flow of the
program or programming errors, such as
eTrO
from simple errors such as
S that can cause exceptions can range index, etc. to serious
opening an invalid array
inva file for reading,
tunning
unning out valid
oh of memory.
182
Vipul's Object Oriented Programming
with
Exceptions can be classified into two types,
namely, synchronous exceptions
asynchronous exceptions. The exceptions that occur at specific program statements
called synchronous exceptions. For Example, deleting from an
empty list, invalid ar
index, stack overflow, etc. are synchronous exceptions.
On the other hand, the exceptions that are issued by external sources
which a
beyond the control of the program are called asynchronous exceptions. For Example th
hardware interrupts such as pressing ctrl+c to interrupt a program is an asynchronou
exception.
C++ provides an efficient exception handling mechanism to handle synchronous
exceptions.
4.3.2 Basics of Exception Handling, Exception Handling Mechanism:
Conventional error-handling mechanism has few limitations such as:
(1) The function that checks the errors has to be called explicitly. Thus, it is difficult to
handle the errors that occur in a class constructor as the constructor is called
implicitly. Hence, this method is not suitable for classes. In other words, this
method does not guarantee that run-time errors are actually caught and handled.
(2) It does not provide a way to separate the error-handling code
from the code writente
to handle the other tasks of the program. This makes it
difficult to read and wrle e
the code.
handling mechanism was introduced in
To overcome these limitations, an exception
exception handling mechanism not only guarantees the detection and
C++ in 1989. C++ a way to separate the error-handling
code
but also provides
handling of run-Time errors makes the program less complex, more readable
and
atn
rest of the program. This Moreover,
from the is not interrupted for
checking errors.
efficient, as the normal execution path
automatically whenever an error occurs.
is invoked
the error-handling routine uses three keywords, 'try', "throw and
mechanism mainly is containedin ec
C++ exception handling for the exceptions
A set of statements that needs to be monitored prefixed by the keyword i
catch'. curly braces and
try block. The try block is surrounded by the thrown
block, it is thrown using excepfion
the within the try
t
exception occurs block, which handles
the
try. Whenever an control to the catch keywords
statement. This passes thestatement and the catch block are prefixed by the
appropriately. The throw
respectively.
throw and catch

r21971
Proo
Programming and ExNception Handling in C++
Vemplate
ate V"Y"Y 189
HandinE,
Eile Try Block
Detects the statement
that contains an exception

Throw Point
Statement that causes
an exception Exception
object passes
to catch block

Catch Block
Catches and handles
the exception appropriately

Try-Throw-Catch Mechanism
also called the exception handler and it must immediately follow
The catch block is
try block that throws
an exception. Syntax is:
the
//try block
try

throw exception; //throw statement

catch (data type parameter) //catch block

exception thrown using the throw statement is the object that transmits the
The
information about the exception. This object is known as an exception object. Once an
exception is thrown, the control is automatically transferred to the catch
block and the
try block is terminated. If the data type of the exception object matches with
the data
If an
ype of the parameter specified in the catch block, the catch block is executed.

not found, the standard library function terminate () is invoked,


prate match is
the program abnormally.
nch by default calls the abort () function to terminate is executed, an exception
Ever, it is not necessary that every time the program
Ab. lt an exception does not occur, the catch
OCCurs. block is skipped and the control passes
the statement
mmediately following the catch block.
Prog
frogram to
emonstrate Exception Handling Mechanism:
includeeiostream.h>
includecconio.h>

void main0

clrscr();
int n r
Vipul's" Object Oriented
Programmingr.
cout<<"Enter percentage:" rlecaa
cin>>n;
try

if(neo 1 n>100)
throw (n);
else
cout<<"\nYour Percentage: "<<n;
jcatch(int i)

cout<"\nInvalid Percentage! !!!!!!"; nu


getch O:

Output Whene
Enter percentage: 56 ement
Your Percentage: 56
Again if Executed throw
Enter percentage: 231
Invalid Percentage!!!!!! throw
in addition to main ( block can also be placed in any other user-det
), the try Thear
function. In this case, the try block is localized to the function. eine
Program to demonstrate Defining a try block inside a user-Defined Function: iton
include<iostrean.h> aemen
include<conio.h
Note
void suaCint n)
hetry b
e hunc
static int s=0;
try
ce tha
if(n>0) rOW p
S=5+n;
STmtax:
else
throw(n)D; retur
Ilfun
}catch(int i)

cout<"\n Exception encountered !!!!! Negative Number: "


<< thr
cout<<"\n Sum of
positive numbers: "<<s;

void main)

cirscrO; unc
int x;
do

cout«<"\nEnter a number:"; tc
cin>x;
sum(x);
Programming and Exception Handling in C++
empatee
191
HanonB
Jh1le(XO); y1 7
ife
getch

Oufput;umber
number:
Entera number 5
a
Ente number: 4
a
Enter number: 1
Enter a -9
Enter a number:
Enter a Negative Number:-9
encountered !!!!!
numbers: 15
!!!
ENception
sitive exception
pos ption ocurs it is thrown using the throw statement. The throw
of er
SUaWheneveer an
written in any of these forms:
can
statement be
(exception);
throw exception;
throw
throw; 'exception' used with the throw statement can be either of a built-in
argument etc, or a 1ser-defined data type, such as class, struct, etc. In
The
as int, oat, throw
type such constants can also be used with the throw statement. The
data
to
variables, Ised to rethrow the exception caught by the catch
argument is
tion: ada without any
statement with
block. exception should always be thrown from within
necessary that the
ate that it is not function defined outside the try block. However,
a
block. It can also be thrown by must be called within the try block. The point
the try the exception statement is executed is called the throw point.
the function throwing
within the function at
which the throw catch block, the control cannot return to
the
exception is thrown to the be executed.
Note that once an throw statement will not
That is, any
statement after the
throw point.
Syntax: (parameter-1ist)
returntype functionName
/function throwing an
exception

throw exception;
//try block

try
Name O
function
functionName ) // call to
block
//catch
atch (data type paramee
Vipul'shM
ject ntedProgramming
192

Throwing an
tr block:
side the try
exceptionOutside wnh Monen
'rogram to demonstrate c
#include«iostream.h>
#inc1ude<conio.h> taa

void
int s-0;
sum(int n)
r
if(n>0)
S=S+n;
else
throw(n):

void main()
Lianple
clrscr)
WAP
int X
try neren
{
do
nacuge

cout««"\nEnter a number:
i : ais
cin>>x;
sum(x); ad
Jwhile(x>0);
Jcatch(int it n
i)

cout«"\n Exception encountered


cout<"\n Sum of positive !!!!! Negative Number: "

numbers:"<<s;9r <<i;
getch Os
if(
thr
Output: catc
Enter a number: 12
Enter a number: 23 coUT
Enter a number: 33
Enter a number:
Enter a number: 21
Enter a number:
Exception
1
-5 n Uutp

Ster
Sum of
encountered
!!!!! Negative
positive numbers: is
Number: ltip
When an 90 -5
handles exception
the exception is thrown, it
try is written needs to
be handled
in the catch
block. For appropriateiy de that
if (n<0) Example,
throw
(n);
catch (int)

cout <"In
Number
is negative

I Exception.
occurrad"1
Exception Handling in Ct+ 193
aramming and
Prog
1emplate
argument is.specified, then that argument can be used
HananE: me
nar of the in

it the
gileHowever,
block.
catch
Bxample
theFor
try (n)
throw (r
Cnc0)
if
catch
(int a) a << 1S negative'";
umber "<<
<<"
cOut is not
user and throw an exception if the number
the
Example accept a number from
to
WAPnumber.
even
#incTude<iostream.h>
an
#inc1ude<conio. h>

main()
void
{ number: ";
int n
cout<"Enter a
cin>>n;

try
ifC(n%2)!=0)
throw(n)D;
a)
Jcatch (int
cout<<"\n"<<a<<" is not even";

Output:
Enter a number:
5 different types of
blocks to handle
5 is not even
Multiple Catch B1ocks: providing multiple catch
allows
aiso
exceptions.
try
Statements
Theax throw
//Multiple
Catch Cdata_type1 argument

argumentz)
atch Cdata type2
194 Vipul'sM Object
OrientedProgramming

catch (data_typeN argumentN) with


, o

Note that there is only one try block try block in which multiple
thrown and
an depending on the type of exception thrown, a particular captione
executed.
bloc
for eran exception is thrown, the catch blocks are searched in
se
appropriate match. The first catch block whose data type matches quential
Or an appropriate is
exception is with t Orde
orde
der
executed and other catch blocks are skipped. Once the exe type
appropriate catch block pe oi
following the gets over, the control passes to the statement
last catch block. If an appropriate match is not imm Of the
immediately
terminates abnormally. found, the program
rogram to demonstrate
#include<iostream.h> Catching Multiple Exceptions:
#include<conio.h>
void MulCatch(int
n)
try

if Cn%2=0)
throw 1;
else
throw 1.0;
catch(int)
cout<"\n Number is
divided by 2";
CatchCdouble)
Cout"\n Number is not divided
by 2";
void main0

clrscr();
intx,y
cout<e"nEnter
cin>>x>y; two numbers:"S
Mu1Catch
(x);
MulCatch(y);
l sip1ktaTlhio
getch);
Output:
Enter two numbers:
3

Number
is not divided
Number
is divided by 2 by 2 Icatch (double)
I/catch called
(int) called
Programming a Exception Handling in C++

Template
Temo
Hanon&
Exceptio
Exceptions: 195

ching All
A11

e atcn not possible to predict all types of exceptions that can occur
1
Sometinmit ecution and. n
and hence, separate catch blocks cannot
be provided to
during
cAS, a single catch handle
block to handle multiple all
progzar
ions. In
exceptto
exceptions can be
the
he
detinea.
Syntax:
catch (-
emonstrate Catching All Exceptions:
7ude1OStream.h
Program h>
Tudeconio.h>
#inc
pinc n)
MuTCatch(int
oid
try
ifCn%2-=0)
throw 1;
else 1.0;
throw
catch(...)
Caught an exception";
cout<<"\n

void mainC
clrscrO;
int n,m; numbers: ";
cout<<"\nEnter two
cin>>n>>m;
Mu1Catch (n);
Mu1Catch(m);
getch ();

Output:
Enter two numbers:

Caught an exception processing it.


Caught an exception_
without exception. As
exception
an same exception.
4.3.4
hrowing an Exception:block to rethrowhancdlers to
access the
rethrow an
closing
C++ also allows a catch multiple is used to next enclo
owS gument to the
Rethrowing ception allowswithout any ag block, passes
catch
stated earlier,
a throw statement
rethrownby the
The
ception, which is
Vipul's Ooect ogramming
Oriented Pro
with
try/catch
nat try/catch
196
the catch block of that ence. c
caught by at an exception can only be
Note that. Noe
try/catch sequence and is sequence.
inside that block berethrown
catch
that catch block of that try/ from any function called
from within a catch block or Exception:
Rethrowing an
rogram to demonstrate
#include<iostream.h>
#include<conio.h>

void Mu1Catch (int n)

try

if(n%2=0
throw 1;
Fcatch(int)
.

coute"\n Number divided by 2"; throw;


}

void main)
clrscr)
int n;
Cout"\nEnter a number:";
cin>>n

Mu1CatchCn)
YcatchCint)

cout"nException rethrown";
coutee"nRemainder is
zero"
getchO

Output:
Enter a number
Number divided by
Exception rethrown2
Remainder zero
is
43.5 Exception
Handlingin
In addition to Classes:
classes built-in data types,
can also
abject of be caught exceptions
the class as and handled. of user-defined as
argument. exception In this case, data ty
and the
catch block the throw expressi oWSan
Ssion throws
an
accepts an as
ject of the class
object
Excep Handling in C++
amming and
emplate 197

HanalnB, strate
onstrate Catching Exceptions of the class type:
dennor
ile 1ude<10stream.h>
to
progran7
ude<con70.h>
nc
nc1u
even
class
int
pub7ic:
n
even()

n-0
(int x)
yoid
getdata
n=X;
(n%2!=0)
if
throw
even();
elsecout<<"\n "<< n <<" divided by 2";

void
main)

int a
even e number:";
cout<<"\nEnter a
cin>>a;
try

e.getdata(a);
catch (even)
caught !!!!";
cout<"\n Exception by 2";
cout«<"\n" << a <<" not divided

getch ();

Output
Enter a number: 3
Exception caught !!!!!
Bnot divided by 2 the
exceptions, which occur while creating
a situation may arise that
the
es
ine a.class, need to be
handled. In such situation,
the throw
an exception must be thrown
statement inside the constructor
4 e constructor of the class. However, case, a new entity called
the
of class. In this
exception annot
éxcenH throw the object of the samethrow statement throws an object of the
class to be created. Now the accepting a parameter or Ype
excep
eedsWhich handled by the catch
is
block
ACeption
exception lclass.
Vipul's" Object Orle
198
Prownine,
either globally or in the Duh: section vinthe
defined
An cxception class can be
exception class can be either
ther emply
Class. Moreover, the body of the or can
ol anuther
data members or member function cOntain
'rogram to demonstrate Defining an Exception Class Inside
ide Anot
Another
Cla
#1nclude<iostream.h>
include«conto.h>
class even

1nt n;
pub1ic:
class check_even

void getdata (int x)

n X;
if(n%2!-0)
throw check-even );
Tain
else
Cout<<"\n "<< n <<" divided by 2";
iat a

void main()

int a;
even e;
cout<"\nEnter a number: ";
cin>>a;
try

e.getdata(a);
3catch(even:: check_even)
cout««"\n Exception caught 1";
cout<<"\n" << a <<" not divided by 2";

getch();
Rapu
ter a
Output: Beivek

Enter a number: 5
Exception caught !1!
5 not divided by 2
4.3.6 Exception Handling in Base
and Derived Classes:
While handling exceptions that proper
involve base as well as derived cclasses, derived
ordering of catch blocks is necessary. A
catch block handling the exceptio
class should be placed betore the base class eption
handler is placed before the derived exception handler. If the base handler
class exception handler, the base
Template PrograHl
Template
Hanan8, derived exceptions and
S 199
the derived class
ite all the handler will
not be
es
Ccatches
ecuted.
dem rate Exception Handling in Base and Derived
exe to
#inc7ude<1Ostream h>
Classes:
Progran
incuaecconio.hs
integer
class
1ic in
:pub7jc integer
even
c1ass
n;
int
public:
even(int x)

n=X

main0
void

int a;
cout<<"\nEnter a number:'
cin>>a
try
if(a%2!=0)
throw even(a);
catch (even)
Exception caught --->"
coutee"\n Derived class

catch (integer)
caught --->";
cout<"\n Base Class Exception
getch 7
Output:
Enter a number: 9
Derived class Exception caught
Self-Practice
Question Bank for
mechanism.
(1) Write
(2)
a short note on C++ eXception handlingused?
3) situations is catch with ellipsis (....)
In which
nen do we use multiple catch blocks?
TWhat
(5) How is an exception object?
are exception handled in classes?

You might also like