Unit V
Unit V
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‖;
}
}
{
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();
…
..
};
example:
Input n numbers into an array and print the element is ascending order.(array sorting)
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;
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