0% found this document useful (0 votes)
2 views5 pages

Unit V

The document discusses exception handling in C++, detailing the use of the throw, try, and catch constructs to manage errors in programs. It explains synchronous and asynchronous exceptions, provides examples of exception handling, and introduces the concept of containership in C++. Additionally, it covers templates for generic programming, including function and class templates, and concludes with an overview of console I/O operations.

Uploaded by

shashankgujrati1
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)
2 views5 pages

Unit V

The document discusses exception handling in C++, detailing the use of the throw, try, and catch constructs to manage errors in programs. It explains synchronous and asynchronous exceptions, provides examples of exception handling, and introduces the concept of containership in C++. Additionally, it covers templates for generic programming, including function and class templates, and concludes with an overview of console I/O operations.

Uploaded by

shashankgujrati1
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/ 5

UNIT V throw construct:

The keyword throw is used to raise an exception when an error is generated in the comutation. the
Exception Handling: throw expression initialize a temporary object of the typeT used in thorw (T arg).
syntax:
throw T;
Exception refers to unexpected condition in a program. The unusual conditions could be faults,
causing an error which in turn causes the program to fail. The error handling mechanism of c++ is
catch construct:
generally referred to as exception handling.
The exception handler is indicated by the catch keyword. It must be used immediately after the
Generally , exceptions are classified into synchronous and asynchronous exceptions.. The exceptions
which occur during the program execution, due to some fault in the input data or technique that is not statements marked by the try keyword. The catch handler can also occur immediately after another
catch Each handler will only evaluate an exception that matches.
suitable to handle the current class of data. with in a program is known as synchronous exception.
Example: syn:
catch(T)
errors such as out of range,overflow,underflow and so on.
{
// error meassges
The exceptions caused by events or faults unrelated to the program and beyond the control of
program are asynchronous exceptions. }
For example, errors such as keyboard interrupts, hardware malfunctions, disk failure and so on.
try construct:
The try keyboard defines a boundary within which an exception can occur. A block of code in which
exception handling model:
an exception can occur must be prefixed by the keyword try. Following the try keyword is a block of
code enclosed by braces. This indicates that the prepared to test for the existence of exceptions. If an
When a program encounters an abnormal situation for which it in not designed, the user may transfer exception occurs, the program flow is interrupted.
control to some other part of the program that is designed to deal with the problem. This is done by
throwing an exception. The exception handling mechanism uses three blocks: try, throw and catch. try
The try block must be followed immediately by a handler, which is a catch block. If an exception is {
thrown in the try block the program control is transferred to the appropriate exception handler. The …
program should attempt to catch any exception that is thrown by any function. The relationship of if (failure)
these three exceptions handling constructs called the exception handling model is shown in figure: throw T;
}
catch(T)
{

try block }
example:
perform operation which maythrow #include<iostream.h>
or invoke external function ifneeded void main()
{
invoke function having throw block int a,b;
cout<<‖enter two numbers:‖;
cin>>a>>b;
if (failure) try
throw object {
if (b= =0)
exception throw b;
else
cout<a/b;
catches all exceptions thrown from
within try block }
catch(int x)
{
cout<<‖2nd operand can‘t be 0‖;
}
}

Array reference out of bound: }


#define max 5 catch (char c)
class array {
{ cout<<‖caught a character…‖;
private: }}
int a[max]; void main()
public: {
int &operator[](int i) test(1);
{ test(-1);
if (i<0 || i>=max) test(0);
throw i; }

else catch all


return a[i]; void test(int x)
} {
}; try{
void main() if (x==1)
throw x;
{
array x; else if (x==-1)
try throw 3.4;
else if (x==0)
{
cout<<‖trying to refer a[1]…‖ throw ‗s‘;
x[1]=3; }
cout<<‖trying to refer a[13]…‖ catch (…)
x[13]=5; {
cout<<‖caught an error…‖;
}
}
catch(int i)
{
cout<<‖out of range in array references…‖;
}
}

multiple catches in a program


void test(int x)
{
try{
if (x==1)
throw x;
else if (x==-1)
throw 3.4;
else if (x==0)
throw ‗s‘;
}
catch (int i)
{
cout<<‖caught an integer…‖;
}
catch (float s)
{
cout<<‖caught a float…‖;
//Sample Program to demonstrate Containership
Containership in C++ #include < iostream.h >
#include < conio.h >
When a class contains objects of another class or its members, this kind of relationship is #include < iomanip.h >
called containership or nesting and the class which contains objects of another class as its members is #include< stdio.h >
called as container class. const int len=80;
class employee
Syntax for the declaration of another class is: {
private:
char name[len];
int number;
Class class_name1 public:
void get_data()
{ {
cout << "\n Enter employee name: ";
——– cin >> name;
cout << "\n Enter employee number:";
——– cin >>number;
}
}; void put_data()
{
cout << " \n\n Employee name: " << name;
Class class_name2
cout << " \n\n Employee number: " <<number;
{ }
};
——– class manager
{
private:
———
char dept[len];
int numemp;
};
employee emp;
public:
Class class_name3
void get_data()
{
{
emp.get_data();
cout << " \n Enter department: ";
Class_name1obj1; // object ofclass_name1
cin >> dept;
cout << "\n Enter number of employees: ";
Class_name2obj2; // object ofclass_name2
cin >> numemp;
}
———-
void put_data()
{
———–
emp.put_data();
cout << " \n\n Department: " << dept;
}; cout << " \n\n Number of employees: " << numemp;
}
};
class scientist
{
private:
int pubs,year;
employee emp;
public:

void get_data() Difference between Inheritance and Containership :


{
emp.get_data(); Containership: Containership is the phenomenon of using one or more classes within the definition
cout << " \n Number of publications: ";
cin >>pubs; of other class. When a class contains the definition of some other classes, it is referred to as
cout << " \n Year of publication: "; composition, containment or aggregation. The data member of a new class is an object of some
cin >> year;
} other class. Thus the other class is said to be composed of other classes and hence referred to as
void put_data() containership. Composition is often referred to as a ―has-a‖ relationship because the objects of the
{
emp.put_data(); composite class have objects of the composed class asmembers.
cout << "\n\n Number of publications: " << pubs;
cout << "\n\n Year of publication: "<< year;
}
}; Inheritance: Inheritance is the phenomenon of deriving a new class from an old one. Inheritance
void main()
{ supports code reusability. Additional features can be added to a class by deriving a class from it and
manager m1; then by adding new features to it. Class once written or tested need not be rewritten or redefined.
scientist s1;
int ch; Inheritance is also referred to as specialization or derivation, as one class is inherited or derived from
clrscr(); the other. It is also termed as ―is-a‖ relationship because every object of the class being defined is
do
{ also an object of the inherited class.
cout << "\n 1.manager\n 2.scientist\n";
cout << "\n Enter your choice: ";
cin >> ch;
switch(ch)
{
case 1:
cout << "\n Manager data:\n";
m1.get_data();
cout << "\n Manager data:\n";
m1.put_data();
break;
case 2:cout << " \n Scientist data:\n";
s1.get_data();
cout << " \n Scientistdata:\n";
s1.put_data();
break;
}
cout << "\n\n To continue Press 1 -> ";
cin >> ch;
}
while(ch==1);
getch();
}
{
Template: if (a>b)
Template supports generic programming, which allows developing reusable software components return a;
such as functions, classes, etc supporting different data types in a single frame work. else
A template in c++ allows the construction of a family of template functions and classes to perform return b;
the same operation o different data types. The templates declared for functions are called class }
templates. They perform appropriate operations depending on the data type of the parameters passed void main()
tothem. {
char ch1,ch2;
Function Templates: cout<<‖enter two characters:‖;
A function template specifies how an individual function can be constructed. cin>>ch1>>ch2;
template <class T> cout<<max(ch1,ch2);
return type functionnm(T arg1,T arg2) int a,b;
{ cout<<‖enter a,b:‖;
fn body; cin>>a>>b;
} cout<<max(a,b);
float p,q;
For example: cout<<‖enter p,q:‖;
Input two number and swap their values cin>>p>>q;
cout<<max(p,q);
template <class T> }
void swap (T &x,T & y)
{ Overloading of function template
T z;
z=x; #include<iostream.h>
x=y; template <class T>
y=z; void print( T a)
} {
void main( ) cout<<a;
{ }
char ch1,ch2; template <class T>
cout<<‖enter two characters:‖; void print( T a, int n)
cin>>ch1>>ch2; {
swap(ch1,ch2); int i;
cout<<ch1<<ch2; for(i=0;i<n;i++)
int a,b; cout<<a;
cout<<‖enter a,b:‖; }
cin>>a>>b; void main()
swap(a,b); {
cout<<a<<b; print(1);
float p,q; print(3.4);
cout<<‖enter p,q:‖; print(455,3);
cin>>p>>q; print(―hello‖,3);
swap(p,q); }
cout<<p<<q;
} Multiple arguments function template:
find sum of two different numbers
example 2: template <class T,class U>
find maxium between two data items. T sum(T a,U b)
template <class T> {
T max(T a,T b) return a+(U)b;
}
void main( )

{
cout<<sum(4,5.5); Class Template
cout<sum(5.4,3); similar to functions, classes can also be declared to operate on different data types. Such classes are
} class templates. a class template specifies how individual classes can be constructed similar to
normal class definition. These classes model a generic class which support similar operations for
different datatypes.

syn:
template <class T>
class classnm
{
T member1;
T member2;


public:
T fun();

..
};

objects for class template is created like:


classnm <datatype> obj;
obj.memberfun();

example:
Input n numbers into an array and print the element is ascending order.(array sorting)

template <class T>


class array
{
T *a;
int n;
public:
void getdata()
{
int i;
cout<<‖enter how many no:‖;
cin>>n;
a=new T[n];
for (i=0;i<n;i++)
{
cout<<enter a number:‖;
cin>>a[i];
}
}
void putdata()
{
for (i=0;i<n;i++)
{ Managing Console I/O
cout<<a[i]<<endl;
}
} Introduction
void sort( )
{ One of the most essential features of interactive programming is its ability to interact
T k; with the users through operator console usually comprising keyboard and monitor. Accordingly,
int i,j; every computer language (and compiler) provides standard
for(i=0;i<n-1;i++) input/output functions and/or methods to facilitate console operations.
{
for (j=0;j<n;j++) C++ accomplishes input/output operations using concept of stream. A stream is a
{ series of bytes whose value depends on the variable in which it is stored. This way, C++ is able to
if (a[i]>a[j]) treat all the input and output operations in a uniform manner. Thus, whether it is reading from a file
{ or from the keyboard, for a C++ program it is simply astream.
k=a[i];
a[i]=a[j]; We have used the objects cin and cout (pre-defined in the iostream.h file) for the input
a[j]=k; and output of data of various types. This has been made possible by overloading the operators >>
} and << to recognize all the basic C++ types. The >>operator is overloaded in the istream class and «
} is overloaded in the ostream class.The
} following is the general format for reading data from the keyboard:
}
}; cin >> variable1 >> variable2 >>… …>> variableN;
voidmain()
{ Where variable1, variable2, are valid C++ variable names that have been declared already.
array <int>x; This statement will cause the computer to halt the execution and look for input data from the
x.getdata(); keyboard. The input data for this statement would be:
x.sort();
x.putdata(); data1 data2. dataN

array <float>y; The input data are separated by white spaces and should match the type of variable in the cin
y.getdata(): list. Spaces, newlines and tabs will be skipped.
y.sort();
y.p utdata(); The operator >> reads the data character by character and assigns it to the indicated location.
} The reading for a variable will be terminated at the encounter of a white space or a character that
does not match the destinationtype.
For example, consider the following code:

int code;
cin >> code;

Suppose the following data is given as input:


1267E
The operator will read the characters up to 7 and the value 1267 is assigned to code. The
character E remains in the input stream and will be input to the next cin statement. The general
format of outputtingdata:
cout << iteml <<item2 <<<< itemN;
The items, item1 through itemN may be variables or constants of any basic types.

The getline () and write () Functions

The put() and get() Functions We can read and display a line of text more efficiently using the line-oriented input/output
The classes istream and ostream define two member functions get() and put() respectively to functions getline() and write(). The getline() function reads a whole line of text that ends with a
handle the single character input/output operations. There are two types of get() functions. We can newline character. This function can be invoked by using the object cin as follows:
use both get(char*) and get(void) prototypes to fetch a character including the blank space, tab and cin.getline(line, size);
the newline character. The get(char*) version assigns the input character to its argument and the This function call invokes the function which reads character input into the variable line. The
get(void) version returns the input character. reading is terminated as soon as either the newline character '\n' is encountered or size number of
Since these functions are members of the input/output stream classes, we must invoke them characters are read (whichever occurs first). The newline. character is read but not saved. Instead, it
using an appropriate object. For instance, look at the code snippet given below: is replaced by the nullcharacter.
char c; For example; consider the following code:
cin.get (c); //get a character from keyboard and assign it to c char name [20] ;
while (c!= '\n') cin.getline(name, 20);
{ Assume that we have given the following input through the keyboard:
cout<<C; //display the character on screen cin.get(c); Neeraj good
//get another character
} This input will be read correctly and assigned to the character array name. Let us suppose the
This code reads and displays a line of text (terminated by a newline character). input is as follows:
Remember, the operator>>can also be used to read a character but it will skip the white spaces and Object Oriented Programming
newline character. The above while loop will not work properly if the statement In this case, the input will be terminated after reading the following 19 characters:
cin >> c; Object Oriented Pro
is used in place of
cin.get (c); After reading the string/ cin automatically adds the terminating null character to thecharacter
Try using both of them and compare the results. The get(void) version is used as array.
follows: Remember,thetwoblankspacescontainedinthestringarealsotakenintoaccount,i.e.
char c; between Objects and Oriented and Pro.
c-cin.getl); //cin.get (c)replaced We can also read strings using the operator >>as follows:
The value returned by the function get() is assigned to the variable c. cin >> name;
But remember cin can read strings that do not contain white space. This means that cin can
The function put(), a member of ostream class, can be used to output a line of text, character read just one word and not a series of words such as ―Neeraj good‖.
by character. For example,
cout << put (‘x’); Formatted Console I/O Operations
displays the character xand
cout << put (ch);
displays the value of variable ch. C++ supports a number of features that could be used for formattingtheoutput. These
The variable ch must contain a character value. We can also use a number as an argument to featuresinclude:
the function put (). For example,  ios class functions andflags.
cout << put (68) ;  Manipulators.
displays the character D. This statement will convert the int value 90 to a char value and display the  User-defined outputfunctions.
character whose ASCII value is 68, The ios class contains a large number of member functions that could be used to format the
The following segment of a program reads a line of text from the keyboard and displays it on output in a number of ways. The most important ones among them are listed below.
the screen.
char c;. Table 10.1
cin.get(c) //read a character
while (c!=‘\n’) Function Task
{ width() To specify the required field size for displaying an output value
cout<< put(c); //display the character on screen cin.get (c ) ;
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.
self() To specify format flags that can control the form of output display
(such as Left-justification and right-justification).
Unself() To clear the flags specified.
Manipulators are special functions that can be included in these statements to alter the format
parameters of a stream. The table given below shows some important! manipulator functions that are
frequently used. To access these manipulators, the file iomanip.h should be included in the program.

Table 10.2
Manipulator Equivalent Ios function
setw() width()
Setprecision() Precision()
Setfill() fill()
setiosflags() self()
Resetiosflags() Unself()

In addition to these functions supported by the C++ library, we can create our own
manipulator functions to provide any special ouput formats.

22 P.T.O

You might also like