100% found this document useful (4 votes)
3K views31 pages

Managing Console I/O Operations: Unit - Iv

The document discusses managing console input/output operations in C++. It covers: 1) C++ stream classes like ios, istream, ostream, and iostream that are used for input/output and inherit properties to define streams for console and files. 2) Unformatted I/O using overloaded >> and << operators to input/output data, and get() and put() functions for single character I/O. 3) Formatted I/O using stream manipulators like setw, setprecision, and setfill to control output formatting by specifying width, precision and fill character.

Uploaded by

Karthik
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
100% found this document useful (4 votes)
3K views31 pages

Managing Console I/O Operations: Unit - Iv

The document discusses managing console input/output operations in C++. It covers: 1) C++ stream classes like ios, istream, ostream, and iostream that are used for input/output and inherit properties to define streams for console and files. 2) Unformatted I/O using overloaded >> and << operators to input/output data, and get() and put() functions for single character I/O. 3) Formatted I/O using stream manipulators like setw, setprecision, and setfill to control output formatting by specifying width, precision and fill character.

Uploaded by

Karthik
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/ 31

UNIT – IV

Managing Console I/O operations

UNIT – IV
4. MANAGING CONSOLE I/O OPERATIONS
4.1.2 C++ Streams:
A stream is a sequence of bytes. It acts either as a source from which the
input data can be obtained or as a destination to which the output data
can be sent.
Input stream:
 It does read operations through keyboard.
 It is uses cin object.
 Cin statement uses >> operator before variable name.
Syntax:
Cin >> variable;
Ex:
int weight;
cin >> weight;
Output stream:
 It displays the contents of variables on the screen.
 It is uses cout object.
 cout statement uses << operator before variable name.
Syntax:
Cout << variable;
Ex:
int weight;
cout << weight;

4.1.3 C++ Stream Classes:


 The c++ input and output system contains a hierarchy of classes
that are used to define various streams to deal with both the
console and disk files.
 These classes are called stream classes.
 These classes are declared in the header file iostream.
UNIT – IV
Managing Console I/O operations

Class name Content


Ios Contains basic facilities that are used by all
(General input other input and output classes.
/ output Also contains a pointer to a buffer object
stream class) (streambuf object)
Declares constants and functions that are
necessary for handling formatted input and
output operations.
Istream inherits the properties of ios. declares input
(input stream) functions such as get( ), getline( ) and read( )
contains overloaded extraction operator >>
Ostream inherits the properties of ios. declares output
(output functions put( ), and write( )
stream) contains overloaded insertion operator <<

Iostream Inherits the properties of ios istream and


(input / output ostream through multiple inheritance and thus
stream) contains all the input and output functions.

Streambuf Provides as interface to physical devices through


buffers. Acts as a base for filebuf class used ios
files.
UNIT – IV
Managing Console I/O operations

4.1.4 UNFORMATTED CONSOL INPUT OUTPUT OPERATIONS:-


a) Overloaded operators >> and <<
 The object cin and cout are used for input and output of data of
various types.

 By overloading operator >> and <<.

 >> Operator is overloaded in the istream class.

 << Operator is overloaded in ostream class.

 This used for input data through keyboard.

get( ) and put( ):


 The classes istream and ostream define two member
functions get() and put() respectively to handle the single
character input/output operations.

 There are two types of get() functions. We can use both


get(char*) and get(void) prototypes to fetch a character
including the blank space, tab and the newline character.

 The get(char*) version assigns the input character to its


argument and the get(void) version returns the input
character.

 The function put(), a member of ostream class, can be used


to output a line of text, character by character.

Ex:
#include<iostream.h>
#include<console.h>
Using namespace std;
int main ( )
{
int count = 0;
char c;
UNIT – IV
Managing Console I/O operations

cout <<”INPUT TEXT\n”;


cin.get (c);
while (c ! = ‘\n’)
{
cout.put (c);
count + +;
cin.get (c);
}
Cout<<”\n Number of characters =”<< count <<
\n”;
return 0;
}

Output:
Input
Object oriented programming
Output
Object oriented programming
Number of characters = 27

b) Getline (char *buffer, int size)


This is a method of cin object and it is used to input a string with multiple
spaces.
Syntax: char x[30];
cin.getline(x,30);
c) Write (char * buffer, int n)
It is a method of cout object. This method is used to read n character from
buffer variable.
Syntax: cout.write(x,2);

4.1.5 FORMATTED CONSOLE I/O OPERATIONS:


C++ supports a number of features that could be used for
formatting the output. These features include:
 ios class functions and flags
 Manipulators
 User – defined output functions
UNIT – IV
Managing Console I/O operations

The ios class contains a large number of member functions


that would help us to format the output in a number of ways. The
most important ones among them are listed.

Function Task
Width ( ) To specify the required field size for displaying an
output value.
Precision To specify the number of digits to be displayed
() after the decimal point of a float value.
Fill ( ) To specify a character that is used to fill the
unused portion of a field.
Setf ( ) To specify format flags that can control the form of
output display (such as left justification and right
justification).
Unsetf To clear the flags specified.
()

a) Manipulators:
 Manipulators are special function that can be included in the I / O
statements to alter the format parameter of a stream.
 Some important manipulator functions that are frequently used.
 To access these manipulators, the file iomanip should be included
in the program.

Manipulators Equivalent ios function


Setw( ) Width( )
Setprecision( ) Presicion( )
Setfill( ) Fill( )
Setiosflags( ) Setf( )
Resetiosflags( ) Unsetf( )

In additional to these standard library manipulators we can create


our own manipulator functions to provide any special output formats.
UNIT – IV
Managing Console I/O operations

Defining field width: width ( ):


The width( ) function to define the width of a field necessary for the output
of an item. Since, it is a member function; we have to use an object to
invoke it, as show below.

Syntax:
Cout.Width(w);
Ex:
Cout.width(5);
Cout<<543<<12<<”\n”;
5 4 3 1 2

The value 543 is printed right – justified in the first columns. The
specification width(5) does not retain the setting for printing the number
12.
Cout.width(5);
Cout<<543;
Cout.width(5);
Cout<<12<<”\n”;

5 4 3 1 2

Ex:
#include<<iostream.h>
Using namespace std;
int main ( )
{
int item[4] = {10, 8, 12, 15};
int cost[4] = {75, 100, 60, 99};
cout.width(5);
cout<<”ITEM”;
cout.width(8);
cout<<”COST”;
cout.width(15);
cout<<”TOTAL VALUE”<<”\n”;
UNIT – IV
Managing Console I/O operations

int sum = 0;
for(int i = 0; i<4; i++)
{
cout.width(5);
cout<<items[i];
cout.width(8);
cout<<cost[i];
int value = item[i] *cost[i];
cout.width(15);
cout<<value<<”\n”;
sum = sum + value;
}
Cout<<”\n Grand Total =”;
cout.width(2);
cout<<sum<<”\n”;
returm 0;
}
OUTPUT:
ITEM COST TOTAL VALUE
10 75 750
8 100 800
12 60 720
15 99 1485
Grand Total = 3755

Setting precision: precision ( ):


 The floating point numbers are printed with six digits after the decimal
point.

 We can specify the number of digits to be displayed after the decimal


point while printing the floating point numbers. Using The precision( )
member function.

Syntax:
UNIT – IV
Managing Console I/O operations

Cout.precision(d);
Ex:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
double f =3.14159;
cout << setprecision (5) << f << endl;
cout << setprecision (9) << f << endl;
return 0;
}

OUTPUT:

The execution of this example shall display:


3.1416
3.14159

Filling and padding: fill ( ):


 When printing values with larger field width than required by the
values, the unused positions of the field with white spaces, by
default.

 Fill( ) function can be used to fill the unused position by any desired
character.

Syntax:
Cout.fill(ch);
Ex:
Cout.fill(‘*’);
Cout.width(10);
Cout<< 5250 <<”\n”;

OUTPUT
UNIT – IV
Managing Console I/O operations

* * * * * * 5 2 5 0

Formatting flags, Bit – fields and setf ( ):


The function width( ) is used, the value (whenever text or number) is
printed right – justified in the field in the field width created.
It is a usual practice to print the text left – justified.
The setf( ), a member function of the ios class, can provide answers to
these and many other formatting questions. The setf( ) (setf stands for set
flags) function can be used as follow:
Syntax:
Cout.setf(arg1, arg2);
Ex:
Cout.setf(ios::left, ios::adjustfield);
Cout.setf(ios::scientific, ios::floatfield);
Ex:
Cout.fill(‘*’);
Cout.setf(ios::left, ios::adjustfield);
Cout.width(15);
Cout<< “TABLE 1” <<”\n”;
OUTPUT:

T A B L E 1 * * * * * * * *

f) Displaying Trailing Zeros and plus sign:


If we print the numbers 10.75, 25.00 and 15.50 using a field width of, say
eight positions, with two digits precision, then the output will be as
follows:
1 0 . 7 5

2 5

1 5 . 5

Ex:
UNIT – IV
Managing Console I/O operations

Cout.setf(ios::showpoint);
Cout.setf(ios::showpos);
Cout.precision(3);
Cout.setf(ios::fixed, ios::floatfield);
Cout.setf(ios::internal, ios::adjustfield);
Cout.width(10);
Cout<< 275.5 << “\n”;
OUTPUT:

+ 2 7 5 . 5 0 0

4.1.6 MANAGING OUTPUT WITH MANIPULATORS:


The header file iomanip provides a set of functions called
manipulators which can be used to manipulate the output formats.
Some manipulators are more convenient to use than their
counterparts in the class ios.
Two or more manipulators can be used as a chain in one statement.
Ex:
Cout<< manip1 << manip2 << manip3 << item;
Cout<< manip1 << item1 << manip2 << item2;

4.2 Working with files

4.2.1 File:
A file is a collection of related data stored in a particular area on the disk.
Programs can be designed to perform the read write operations on these
files.
The following kinds of data communication:
1. Data transfer between the console unit and the program.
2. Data transfer between the program and a disk file.

4.2.2 Classes for file stream operations:


Ofstream: stream class to write on files.
UNIT – IV
Managing Console I/O operations

Ifstream: stream class to read on files.


fstream: stream class to both read and write from / to files.
To perform file processing in C++, handling files <iostream> and
<fstream> must be included in C++ program.

class functions
It sets the file buffers to read and write.
filebuf Member functions: open( ), close( )
This is the base class for fstream,
fstreambase ifstream and ofstream classes.
Member functions: all input and output
functions, open( ), close( ).
It provides input operations for file.
ifstream Member functions: get( ), getline( ), read(
), seekg( ), tellg( ).
It provide output operations for file.
Ofstream Member functions: put( ), write( ), seekp(
), tellg( )
fstream It is an input – output stream class.

4.2.3 Opening and closing a file:


If we want to use a disk file, we need to decide the following things
about the file and its intended use.
1. Suitable name for the name
2. Data type and structure
3. Purpose
4. Opening method
The filename is a string of characters that make up a valid filename for
the operating system. It may contain two parts, a primary name and an
option period with extension.
Ex:
Input.data
UNIT – IV
Managing Console I/O operations

Test.doc
INVENT.ORY
Student
Salary

a) Opening files using constructor:


A constructor is used to initialize an object while it is being created. A file
name is used to initialize the file stream object.
This involves the following steps:
1. Create a file stream object to manage the stream using the appropriate
class. The class ofstream is used to create the output stream and the class
ifstream to create the input stream.
2. initialize the file object with the desired filename.
Syntax: ofstream outfile (“result”);

b) Opening files using open( ):


 The function open( ) can be used to open multiple files that use
the same stream object.
 We may want to process a set of files sequentially.
 Create a single stream object and use it to open each files in
turn.
Syntax: file – stream – class stream – object;
Stream – object. open(“filename”);

4.2.4 Detecting end – of – file:


 Deleting of the end – of – file condition is necessary for preventing any
further attempt to read data from the file.
Syntax: while(fin)
UNIT – IV
Managing Console I/O operations

 An ifstream object, such as fin returns a value of 0 if any error occurs in


the file operation including the end – of – file condition.
 The while loop terminates when fin returns a value of zero on reaching
the end – of – file condition.
Syntax: if(fin1.eof( ) ! = 0)
{
exit(1);
}

4.2.5 Open ( ): file mode:


We have used ifstream and ofstream constructor and the function open( )
to create new files are well as to open existing files.
We used only one argument that was the filename. The second one for
specifying the file mode.
Syntax: stream – object.open(“filename”, mode);

4.2.6 File pointers and their manipulations:


 Each file has two associated pointer known as the file pointers.

 One of them is called input pointer or get pointer.

 Other one is called the output pointer or put pointer.

 The input pointer is used for reading the content of given file
location and output pointer is used for writing to a given file
location.

 Each time an input and output operation takes place the


appropriate pointer is automatically advanced.

Default action
Open a file in read only mode the input pointer automatically set at
the beginning so that we can read the file from start.
Open file write only mode the input pointer the existing contents are
deleted and the output pointer is set at the beginning.
UNIT – IV
Managing Console I/O operations

This enables us to write the file from start.

Functions for manipulation of file pointers:


As we shown file pointer takes place automatically by default. But
how do we move a file pointer to any other desired location.
This is possible only if we can take control of movement of file
pointers ourselves.
The file stream classes support the following function to manage
such situation:
 Seekg( ): move get pointer specific location.(read)
 Seekp( ): move put pointer specific location.(write)

 tellg( ): Gives the current position of the get pointer.


 tellp( ): Gives the current position of the get pointer.

Specifying the offset:


To move a file pointer to a desired location using the “seek”
functions. The argument to these functions represents the absolute
position in the file.
Syntax: seekg(offset, refposition);
Seekg(offset, refposition);
The parameter offset represents the number of bytes the file pointer is to
be moved from the location specified by the parameter refposition.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file

4.2.7 Sequential input and output operations:


 The file stream classes support a number of member functions for
performing the input and output operation on file.
 One pair of the get( ) and put( ) are designed for handling a single
character at a time.
UNIT – IV
Managing Console I/O operations

 Another pair of functions write( ) and read( ) are designed to write and
read block of binary data.

Put ( ) and get ( ) functions:

get( ) function is defined in the istream class in order to handle single


character inputs.
It can implement as:
Syntax: cin.get(ch);

put( ) function is defined in the ostream class in order to handle single


character output.
It can implement as:
Syntax: cout.put(‘x’);
Write ( ) and read ( ) functions:
The function write( ) and read( ), unlike the functions put( ) and get( ),
handle the data in binary form.
This means that the values are stored in the disk file in the same
format in which they are stored in internal memory.
Int value 2594 is stored in the binary and character formats. An int
takes two bytes to store its value in the binary form.
But a 4 digit int will take four bytes to store it in the character form.
Syntax: infile.read((char*)& V, sizeof (v));
outfile.write((char*)& V, sizeof (v));
These functions take two arguments:
The first is the address of the variable V.
The second is the length of that variable in bytes.

Reading and writing a class object:


The class objects are the central elements of c++ programming, it is
quite natural that the language supports features for writing to and
reading from the disk files objects directly.
The binary input and output functions read( ) and write( ) are
designed to do exactly this job.
UNIT – IV
Managing Console I/O operations

These functions handle the entire structure of an object as a single


unit, using the computer’s internal representation of data.

4.2.8 Updating a file: random access:


Updating is a routine task in the maintenance of any data file. The
updating would include one or more of the following tasks:
 Displaying the contents of a file.
 Modifying an existing item.
 Adding a new item.
 Deleting an existing item.

4.2.9 Error handling during files operations:


We have been opening and using the files for reading and writing on the
assumption that everything is fine with the files.
For instance: one of the following things may happen when dealing with
the files:
1. A files which we are attempting to open for reading does not exist.
2. The file name used for a new file may already exist.
3. We may attempt an invalid operation such as reading past the end – of
– file.
4. There may not be any space in the disk for storing more data.
5. We may use an invalid file name.
6. We may attempt to perform an operation when the file is not opened
for that purpose.
The c++ file stream inherits a “stream_state” member from the class ios.
This member record information on the status of a file that is being
currently used.
The class ios support several member functions that can be used to read
the status recorded in a file stream.
eof( )
fail( )
UNIT – IV
Managing Console I/O operations

bad( )
good( ). Etc..

4.2.10 Command line arguments:


C++ support a feature that facilities the supply of argument to the main( )
function.
These arguments are supplied at the time of invoking the program.
They are typically used to pass the names of data files.
Eg:- exam data result.
C > exam data results
Here, exam is the name of the file containing the program to be
executed, and data results are the filenames passed to the program
as command – line – arguments.
The command line arguments are typed by the user and are
delimited by a space.
Main( int argc, char*argv[ ])
argc – Arguments counter
argv – Argumrnts vector

4.3 TEMPLATES
4.3.1 Introduction
The template is a feature of the c++ programming language that allows
function and classes to operate with generic types.
The c++ standard library provides many useful functions within a
framework of connected templates.
C++ templates come in two flavors:
Functions templates: C++ function templates are those functions which
can handle different data types without separate code for each of them.
Class templates: C++ class templates are used where we have
multiple copies of code for different data types with the same logic.
Class templates:
 A singe code segment represents a set of related classes.
- Called parameterized types.
UNIT – IV
Managing Console I/O operations

Syntax: template<class type>


Class declaration
 A template instantiation can be created with either a built – in or user
– defined type.
 The function members of a class template are considered function
templates.
4.3.2 Class templates with multiple parameters:
We can use more than one generic data type in a class template.
They are declared as a common – separated list within the template
specification as show below:
Statement:
Template<class T1, class T2, ….>
Class classname
{
. . . . . ..
. . . . . . . (body of function)
. . . . . . .
}

Ex:
#include<iostream.h>
Using namespace std;
Template<class T1, class T2>
Class Test
{
T1 a;
T2 b;
Public:
Test(T1 x, T2 y)
{
a=x;
b=y;
void show( )
{
Cout<<a <<”and”
};
Int main( )
{
Test<float, int> test1(1.23, 123);
Test<int, char>test2(100,’w’);
UNIT – IV
Managing Console I/O operations

test1.show( );
test2.show( );
return 0;
}
OUTPUT
1.23 and 123
100 and w

4.3.3 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.
Normally, if you need to perform identical operations on two or more
types of data, you use function overloading to create two functions with
the required function declaration.
However, a better approach would be to use function templates because
you can perform the same task writing less and maintainable code.
Syntax:
template<class T>
retuenype functionname(arguments of type T)
{
// . . . . . .
// body of function
// with type T
// wherever appropriate
// . . . . . .
}

Ex:
#include<iostream.h>
Using namespace std
template<class T>
void swap(T&x, T&y)
{
T temp = x;
X = y;
Y = temp;
}
Void fun(int m, int n, float a, float b)
UNIT – IV
Managing Console I/O operations

{
Cout<<”m and n before swap:”<<m <<” “<<n <<”\n”;
Swap(m, n);
Cout<<”m and n after swap:”<<m <<” “<<n <<”\n”;

Cout<<”a and b before swap:”<<a <<” “<<b <<”\n”;


Swap(a, b);
Cout<<”a and b after swap:”<<a <<” “<<b <<”\n”;
}
int main( )
{
Fun(100, 200, 11.22, 33.44);
return 0;
}

OUTPUT:
m and n before swap: 100 200
m and n after swap: 200 100
a and b before swap: 11.22 33.439999
a and b after swap: 33.439999 11.22

4.3.4 Function templates with multiple parameters:


We can use more than one generic data type in the template statement,
using a common – separated list as show below:
Statement:
Template<class T1, class T2, ….>
returntype functionname(argument of types T1, T2, . . . .)
{
. . . . . ..
. . . . . . . (body of function)
. . . . . . .
}

4.3.5 Overloading of template function:


A template functions may be overloaded either by template functions or
ordinary functions of its name. in such cases, the overloading resolution is
accomplished as follows:
1. Call an ordinary function that has an exact match.
2. Call a template function that could be created with an exact match.
UNIT – IV
Managing Console I/O operations

3. Try normal overloading resolution to ordinary functions and call the


one that matches.
An error is generated if no match id found. Note that no automatic
conversions are applied to arguments on the template functions.
Ex:
#include<iostream.h>
#include<conio.h>
Template<class A>
Void show(A c)
{
Cout<<”\n Template variable c =”<<c;
}
Void show(int f)
{
Cout<<”\n integer variable f =”<<f;
}
int main( )
{
Clrscr( );
Show(‘C’);
Show(50);
Shoe(50.25);
Return 0;
}
OUTPUT:
Template variable c = C
integer variable f = 50
Template variable c 50.25

4.3.6 Member function templates:


When we created a class template for vector, all the member functions
were defined as inline which was not necessary.
We could have defined them outside the class as well.
But remember that the member functions of the template classes
themselves are parameterized by the type argument (to their template
classes) and therefore these functions must be defined by the function
templates.
It takes the following general form:
Statement:
UNIT – IV
Managing Console I/O operations

Template<class T>
returntype classname<T> :: functionname(arglist)
{
// . . . . . .
// function body
// . . . . . .
}
Ex:
// class template . . . . .
template<class T>
class vector
{
T* v;
Int size;
Public:
Vector(int m)
Vector(T* a);
T operator*(vector &y);
};
template<class T>
vector<T> :: vector(int m);
{
V = new T[size = m];
For(int i = 0; i<size; i++)
V[i]; = 0;
}
template<class T>
vector<T> :: vector(T* a);
{
For(int i = 0; i<size; i++)
V[i]; = a[i];
}
template<class T>
T vector<T> :: operator +(int m);
{
T sum = 0;
For(int i = 0; i<size; i++)
Sum += this -> v[i] * y.v[i];
return sum;
}

4.3.7 Non – type template arguments:


UNIT – IV
Managing Console I/O operations

We have seen that a template can have multiple arguments. It is


also possible to use non – type arguments.
That is, in addition to the type argument T, we can also use other
arguments such as strings, function names, constant expressions
and built – in types.

Consider the following example.


template<class T, int size>
class array
{
T a[size];
};
This template supplies the size of the array as an argument.
This implies that the size of the array is known to the complier at time
itself.
The arguments must be specified whenever a template class is created.
Ex:
array<int, 10> a1; //Array of 10 integer
array<float, 5> a2; //Array of 5 floats
array<char, 20> a3; //string of size 20

4.4 EXCEPTION HANDLING


4.4.1 Introduction

 It is very rare that a program works correctly fist time. It might have
bugs.

 The two most common types of bugs are logic errors and syntactic
errors.

 Logic errors: The logic errors occur due to poor understanding


of the problem and solution procedure.
UNIT – IV
Managing Console I/O operations

 Syntactic errors: The syntactic errors arise due to poor


understanding of the language itself.

 We can detect these errors by using exhaustive debugging and


testing procedures.

• Exceptions:

– Indicate problems that occur during a program’s execution.


– Occur infrequently.
• Exception handling:

– Can resolve exceptions


• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
– Makes programs robust and fault-tolerant

4.4.2 Basics of Exception Handling:

Exceptions are of the two kinds:

i) Synchronous exception: Errors such as “out – of - range” and


“over – flow” belong to the synchronous type exceptions.

ii) Asynchronous exception: The errors that are caused by


events beyond the control of the program (such as keyboard
interrupts) are called asynchronous type exceptions.

The mechanism suggests to separate error handling code that


performs the following tasks:

1. Find the problem (Hit the exception).

2. Inform that an error has occurred (Throw the exception).

3. Receive the error information (catch the exception).


UNIT – IV
Managing Console I/O operations

4. Take corrective actions (Handle the exception).

The error handling code basically consists of two segments:

– To detect errors and to throw exceptions.

– To catch the exceptions and to take appropriate actions.

4.4.3 Exception Handling Mechanism:

C++ exception handling mechanism is basically built upon the


keywords.

 try: A try block identifies a block of code for which


particular exceptions will be activated. Its followed by one or
more catch block.

 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
program. The catch keyword indicate the catching of an
exception.

4.4.4 Throwing Mechanism:

When an exception that is desired to be handled is detected, it is


thrown using the throw exception statement in one of the following
forms.

Statement:

throw (exception);

throw (exception);

throw; //used for rethrowing an exception


UNIT – IV
Managing Console I/O operations

 The operand object exception can be of any type, including constant.

 It is also possible to throw an object not intended for error handling.

 Throw point can be in a deeply nested scope within a try block or in a


deeply nested function call.

 In any case, control is transferred to the catch statement.

4.4.5 Catching Mechanism:

– The type indicates the type of exception the catch block handles.

– The parameter arg is an optional parameter name.

Statement:

catch(type arg)
{
// statements for
// managing exceptions
}

– The catch statement catches an exception whose type matches with


the type of the catch argument.

– If the parameter in the catch statement is named, then the parameter


can be used in the exception handling code.

– If a catch statement does not match the exception it is skipped.

– More than one catch statement can be associated with a try


block.

4.4.5 (a) Multiple catch statement:

* When an exception is thrown, the exception handlers are searched


in Order for a match.
UNIT – IV
Managing Console I/O operations

* The first handler that yields a match is executed.

* If several catch statement matches the type of an

* Exception the first handler that matches the exception type is

executed.

Statement:

try
{
//try block
}
Catch (type1 arg)
{
//catch block1
}
Catch (type1 arg)
{
//catch block2
}
Catch (typeN arg)
{
//catch blockN
}

4.4.5 (b) Catch all exception:

In some circumstances we want an exception handler to catch all


exception instead of just a certain type.

This easily accomplished by using this form of catch.

One catch statement can catch all exception instead of a certain type
alone.

This could be done by defining the catch statements using ellipse as


follows.

Statements:

Catch(. . . . )
{
UNIT – IV
Managing Console I/O operations

//statements for processing


// all exception
}
4.4.6 Rethrowing an Exception:

A handler may decide to rethrow the exception caught without


processing it.

In such a case we have to invoke throw without any arguments as


shown below

Throw;

This causes the current exception to be thrown to the next enclosing


try/catch sequence and is caught by a catch statement listed after the
enclosing try block

4.4.7 Specifying Exception:

It is possible to restrict a function to throw certain specific exceptions


by adding a throw list clause to the function definition.

The type-list specifies the type of exception that may be thrown.

Throwing any other kind of exception will cause abnormal program


termination.

If you want to prevent a function from throwing any exception, you may do so
by making the type-list empty.

Statement:
type function(arg – list) throw (type – list)
{
......
...... function body
......
}
UNIT – IV
Managing Console I/O operations

4.4.8 Exception in constructors and destructors:

A copy constructor is called in exception handling when an exception


is thrown from the try block using the throw statement.

The copy constructor mechanism is applied to initialize the temporary


object.

Destructors are also executed to destroy the object.

If an exception is thrown from the constructor, destructors are called


only for those objects that are completely constructed.

Ex:
Write a program to use exception handling with constructor and destructor.
#include<iostream.h>
#include<process.h>
Class number
{
float x;
public:
number(float);
number() {};
~number()
{
Cout<<”\n in destructor”;
}
Void operator++(int) //postfix notation
{
X++;
}
Void operator—() //postfix notation
{
--x;
}
Void show()
{
Cout<<”\n x=”<<x;
}
};
number::number(float k)
UNIT – IV
Managing Console I/O operations

{
if (k==0)
Throw number();
else
x=k;
}
Void main()
{
try
{
number N(2.4);
cout<<”\n Before increasing”;
N.show();
cout<<”\n After increasing”;
N++;
N.show();
cout<<”\n After Decrementation”;
--N;
N.show();
number N1(0);
}
Catch (number)
{
cout<<”\n invalid number”;
exit(1);
}
}

OUTPUT:

Before increasing:
X = 2.4
After increasing:
X = 3.4
After Decrementation:
X = 2.4
In destructor
In destructor
Invalid number
UNIT – IV
Managing Console I/O operations

4.4.9 Exception in operator overloading function:

Exception handling mechanism in an operator overloading function


definition to handle system generated or user specified exception
handling.

Which we had overloaded the + binary operator to compute the sum of


two complex numbers.

The following code depicts the handling of user – specified exception of


adding a zero to the complex number object.

Ex:

Class template
{
.
Public:
Class FLAG{ }; //abstract class FLAG
.
.
};
Complex complex :: operator +(complex c)
{
If (c.x==0 && c.y==0)
throw FLAG( );
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}
Catch (complex :: FLAG)
{
Cout<<”Add Zero Exception”;
}
.

You might also like