Ads Unit III
Ads Unit III
Fundamentals:
• General form:
try
{ //try block
}
catch(type1 arg)
{ //catch block
}
..
..
..
catch(typen arg)
{ //catch block
}
UNIT III 1
• General form of the throw statement is:
o throw exception;
Ex:
#include <iostream.h>
int main()
{
cout << "Start\n";
try
{ // start a try block
catch (int i)
{ // catch an error
return 0;
}
UNIT III 2
• Usually the code within a catch statement attempts to remedy an
error by taking appropriate action. If the error cant be fixed,
execution will continue with the statements following the catch.
Ex:
#include <iostream.h>
int main()
{
cout << "Start\n";
try
{ // start a try block
cout << "Inside try block\n";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i)
{ // catch an error
cout << "Caught an exception -- value is: ";
cout << i << "\n";
}
return 0;
}
UNIT III 3
• A try block can be localized to a function. When this is the
case, each time the function is entered, the exception handling
relative to that function is reset.
Ex:
#include <iostream.h>
int main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
return 0;
}
UNIT III 4
Catching Class Types:
• The most common reason that one wants to define a class type for
an exception is to create an object that describes the error
that occurred. This information can be used by the exception
handler to help it process the error.
Ex:
#include <iostream.h>
#include <cstring.h>
class MyException
{ public:
char str_what[80];
int what;
int main()
{
int i;
try
{
cout << "Enter a positive number: ";
cin >> i;
if(i<0)
throw MyException("Not Positive", i);
}
catch (MyException e)
{ // catch an error
cout << e.str_what << ": ";
cout << e.what << "\n";
}
return 0;
}
UNIT III 5
Using Multiple Catch Statements:
Ex:
#include <iostream.h>
int main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
return 0;
}
UNIT III 6
Handling derived Class Exceptions:
Ex:
#include <iostream.h>
class B
{
};
class D: public B
{
};
int main()
{
D derived;
try
{
throw derived;
}
catch(B b)
{
cout << "Caught a base class.\n";
}
catch(D d)
{
cout << "This won't execute.\n";
}
return 0;
}
UNIT III 7
Exception Handling Options:
Xhandler(0);
Xhandler(1);
Xhandler(2);
return 0;
}
UNIT III 8
2. Restricting Exceptions:
Ex:
#include <iostream.h>
int main()
{
cout << "start\n";
try
{ Xhandler(0); // try passing 1 and 2 to Xhandler()
}
catch(int i)
{ cout << "Caught an integer\n";
}
catch(char c)
{ cout << "Caught char\n";
}
catch(double d)
{ cout << "Caught double\n";
}
return 0;
}
UNIT III 9
• Attempting to throw an exception that is not supported by a
function will cause the std library function unexpected()
to be called.
• That is, a try block within a function may throw any type
of exception so long as it is caught within that function.
3. Rethrowing an Exception:
UNIT III 10
Ex:
#include <iostream.h>
void Xhandler()
{
try
{
throw "hello"; // throw a char *
}
catch(const char *)
{
// catch a char *
cout << "Caught char * inside Xhandler\n";
}
}
int main()
{
cout << "Start\n";
try
{
Xhandler();
}
catch(const char *)
{
cout << "Caught char * inside main\n";
}
return 0;
}
UNIT III 11
terminate()
UNIT III 12
Ex:
void my_Thandler()
{
cout << "Inside new terminate handler\n";
abort();
}
int main()
{
// set a new terminate handler
set_terminate(my_Thandler);
try
{
cout << "Inside try block\n";
throw 100; // throw an error
}
catch (double i)
{ // won't catch an int exception
// ...
}
return 0;
}
UNIT III 13
unexpected()
uncaught_exception()
UNIT III 14
Note:
do
{
cout << "Enter numerator (0 to stop): ";
cin >> i;
cout << "Enter denominator: ";
cin >> j;
divide(i, j);
} while(i != 0);
return 0;
}
UNIT III 15
C++ CONSOLE AND FORMATTED I/O
C++ Streams
• Because all streams behave the same, the same I/O functions can
operate on virtually any type of physical device.
UNIT III 16
basic_ios is used as a base for several derived classes, including
basic_stream, basic_ostream and basic_iostream.
These classes are used to create streams capable of input, output and
input/output respectively.
• The ios class contains many member functions & variables that
control or monitor the fundamental operation of a stream.
Formatted I/O
There are 2 related but conceptually different ways that you can
format data.
UNIT III 17
Formatting using ios Members
Each stream has associated with it a set of format flags that control
the way information is formatted.
UNIT III 18
Setting the format flags
cout.setf(ios::showpos);
return 0;
}
UNIT III 19
An overloaded form of setf()
Eg:
#include <iostream.h>
int main( )
{
cout.setf(ios::showpoint | ios::showpos, ios::showpoint);
return 0;
}
Eg:
#include <iostream.h>
int main()
{
cout.setf(ios::hex, ios::basefield);
return 0;
}
UNIT III 20
Examining the Formatting Flags
fmtflags flags(fmtflags f)
o Bit pattern found in f is used to set the format flags
associated with the stream.
There are 3 member functions defined by ios that set these format
parameters, the filed width, the precision and the fill character.
Default precision is 6.
UNIT III 21
Eg:
#include <iostream.h>
int main()
{
cout.precision(4) ;
cout.width(10);
cout.fill('*');
cout.width(10);
cout.width(10);
cout.width(10);
return 0;
UNIT III 22
Using Manipulators to Format I/O
• To access manipulators that take parameters, include <iomanip.h>
in the program.
• The main advantage of using the manipulators instead of the ios
member functions is that they commonly allow more compact code
to be written.
Eg:
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout << hex << 100 << endl;
cout << setfill('?') << setw(10) << 2343.0;
return 0;
}
• The manipulator setiosflags() performs the same function as the
member function setf().
Eg:
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout << setiosflags(ios::showpos);
cout << 123 << " " << hex << 123;
return 0;
}
• One of the most interesting manipulator is boolalpha. It allows
true & false values to be input & output using the words true
and false rather than numbers.
Eg:
#include <iostream.h>
int main()
{
bool b;
b = true;
cout << b << " " << boolalpha << b << endl;
return 0;
}
UNIT III 23
C++ FILE INPUT/OUTPUT
UNIT III 24
• Filename is the name of the file.
5. ios::out
6. ios::in
Note: The mode parameter provides default values for each type of
stream, as given in the prototype.
UNIT III 25
• To check if a file is successfully opened, use the function
bool is_open(); a member function of fstream, ifstream and
ofstream.
• Simply use the << and >> operators the same way as when
performing console I/O, except that instead of using cin and
cout, substitute a stream that is linked to a file.
Eg:
#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream out("INVNTRY"); // output, normal file
if(!out)
{
cout << "Cannot open INVENTORY file.\n";
return 1;
}
out.close();
return 0;
}
UNIT III 26
Eg:
#include <iostream.h>
#include <fstream.h>
int main()
{
ifstream in("INVNTRY"); // input
if(!in)
{
cout << "Cannot open INVENTORY file.\n";
return 1;
}
char item[20];
float cost;
in.close();
return 0;
}
Unformatted and Binary I/O
• reads a char from invoking stream & puts its value in ch.
UNIT III 27
Eg1: #include <iostream.h>
#include <fstream.h>
int main(int argc, char *argv[])
{
char ch;
if(argc!=2)
{
cout << "Usage: PR <filename>\n";
return 1;
}
while(in)
{ // in will be false when eof is reached
in.get(ch);
if(in) cout << ch;
}
return 0;
}
out.close();
return 0;
}
UNIT III 28
More get() functions
3. int get();
getline()
UNIT III 29
Eg: #include <iostream.h>
#include <fstream.h>
int main()
{
ifstream in(“test”); // input
if(!in)
{ cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while(in)
{
in.getline(str, 255); // delim defaults to '\n'
if(in)
cout << str << endl;
}
in.close();
return 0;
}
Note:
• The typecasts inside the calls to read() & write() are
necessary when operating on a buffer that is not defined as a
char array.
UNIT III 30
• To find out how many characters have been read use the member
function called gcount().
streamsize gcount();
Eg:
#include <iostream.h>
#include <fstream.h>
int main()
{
double fnum[4] = {99.75, -34.4, 1776.0, 200.1};
int i;
out.close();
in.close();
return 0;
}
UNIT III 31
ignore()
Eg:
#include <iostream.h>
#include <fstream.h>
int main()
{
ifstream in("test");
if(!in)
{
cout << "Cannot open file.\n";
return 1;
}
char c;
while(in)
{
in.get(c);
if(in)
cout << c;
}
in.close();
return 0;
}
UNIT III 32
peek() and putback()
• We can obtain the next char in the input stream without removing
it from that stream by using peek().
• int_type peek();
• It returns the next char in the stream or EOF if the end of file
is encountered.
• We can return the last char read from a stream to that stream by
using putback().
flush()
• ostream& flush();
Random Access
UNIT III 33
• The C++ I/O system manages 2 pointers associated with a file.
• Using the seekg() and seekp() functions allows you to access the
file in a nonsequential fashion.
o ios::beg
o ios::cur
o ios::end
o pos_type tellg();
o pos_type tellp();
UNIT III 34
Eg:
#include <iostream.h>
#include <fstream.h>
#include <cstdlib.h>
if(!inout)
{
cout << "Cannot open input file.\n";
return 1;
}
long e, i, j;
char c1, c2;
e = atol(argv[2]);
inout.seekg(j, ios::beg);
inout.get(c2);
inout.seekp(i, ios::beg);
inout.put(c2);
inout.seekp(j, ios::beg);
inout.put(c1);
}
inout.close();
return 0;
}
UNIT III 35
I/O Status
o iostate rdstate();
UNIT III 36
Eg:
#include <iostream.h>
#include <fstream.h>
int main()
{
ifstream in(“test”);
if(!in)
{
cout << "Cannot open input file.\n";
return 1;
}
char c;
while(in.get(c))
{
if(in)
cout << c;
checkstatus(in);
}
in.close();
return 0;
}
i = in.rdstate();
UNIT III 37