Exceptions · Web viewExceptions Exceptions are run time anomalies or unusual condition that a...
Transcript of Exceptions · Web viewExceptions Exceptions are run time anomalies or unusual condition that a...
Exceptions
Exceptions are run time anomalies or unusual condition that a program may encounter
during execution.
Examples:
Division by zero
Access to an array outside of its bounds
Running out of memory
Running out of disk space
Principles of Exception Handling: Similar to errors, exceptions are also of two types. They are as
follows:
Synchronous exceptions: The exceptions which occur during the program execution due
to some fault in the input data.
For example: Errors such as out of range, overflow, division by zero
Asynchronous exceptions: The exceptions caused by events or faults unrelated
(external) to the program and beyond the control of the program.
For Example: Key board failures, hardware disk failures
The exception handling mechanism of C++ is designed to handle only synchronous
exceptions within a program. The goal of exception handling is to create a routine that detects
and sends an exceptional condition in order to execute suitable actions. The routine needs to carry
out the following responsibilities:
1. Detect the problem (Hit the exception)
2. Inform that an error has been detected (Throw the exception)
3. Receive error information (Catch the exception)
4. Take corrective action (Handle the exception)
An exception is an object. It is sent from the part of the program where an error occurs to
the part of the program that is going to control the error
The Keywords try, throw, and catch
Exception handling mechanism basically builds upon three keywords:
try catch throw
The keyword try is used to preface a block of statements which may generate exceptions.
Syntax of try statement:try{
statement 1;statement 2;
}
When an exception is detected, it is thrown using a throw statement in the try block.
Syntax of throw statement
throw (excep); throw excep; throw; // re-throwing of an exception
A catch block defined by the keyword ‘catch’ catches the exception and handles it
appropriately. The catch block that catches an exception must immediately follow the try
block that throws the exception
Syntax of catch statement:
try{
Statement 1;Statement 2;
}catch ( argument){
statement 3; // Action to be taken}
When an exception is found, the catch block is executed. The catch statement
contains an argument of exception type, and it is optional. When an argument is declared,
the argument can be used in the catch block. After the execution of the catch block, the
statements inside the blocks are executed. In case no exception is caught, the catch block
is ignored, and if a mismatch is found, the program is terminated.
Guidelines for Exception Handling
The C++ exception-handling mechanism provides three keywords; they are try, throw ,
and catch. The keyword try is used at the starting of the exception. The throw block is present
inside the try block. Immediately after the try block, the catch block is present. Figure shows the
try, catch, and throw statements.
As soon as an exception is found, the throw statement inside the try block throws an
exception (a message for the catch block that an error has occurred in the try block statements).
Only errors occurring inside the try block are used to throw exceptions. The catch block receives
the exception that is sent by the throw block. The general form of the statement is as per the
following figure.
When the try block passes an exception using the throw statement, the control of the
program passes to the catch block. The data type used by throw and catch statements should be
same; otherwise, the program is aborted using the abort() function, which is executed implicitly
by the compiler. When no error is found and no exception is thrown, in such a situation, the
catch block is disregarded, and the statement after the catch block is executed.
/* Write a program to illustrate division by zero exception. */
#include <iostream> using namespace std;
int main(){
int a, b;cout<<"Enter the values of a and b"<<endl; cin>>a>>b;try{
if(b!=0)cout<<a/b;
else
}throw b;
catch(int i)
{cout<<"Division by zero: "<<i<<endl;
}return 0;
}Output:Enter the values of a and b 20
Division by zero: 0
/* Write a program to illustrate array index out of bounds exception. */
#include <iostream> using namespace std; int main() {
int a[5]={1,2,3,4,5},i;try{
i=0;while(1){
if(i!=5){
}else
cout<<a[i]<<endl; i++;
throw i;}
}catch(int i){
cout<<"Array Index out of Bounds Exception: "<<i<<endl;}return 0;
}
Output:12345Array Index out of Bounds Exception: 5
/* Write a C++ program to define function that generates exception. */
#include<iostream> using namespace std; void sqr(){
int s;cout<<"\n Enter a number:"; cin>>s;if (s>0){
}else{
}}
cout<<"Square="<<s*s;
throw (s);
int main(){
try{
}sqr();
catch (int j){
cout<<"\n Caught the exception \n";}return 0;
}
Ouput:Enter a number:10 Square=100Enter a number:-1 Caught the exception
Multiple catch Statements
It is also possible that a program segment has more than one condition to throw an
exception. In such cases, we can associate more than one catch statement with a try (similar to
switch statement). The format of multiple catch statements is as follows:
try{
}// try block
catch (type1 arg){
// catch section1}catch (type2 arg){
// catch section2}. . . . . . .. . . . . . .
catch (typen arg){
// catch section-n}
When an exception is thrown, the exception handlers are searched in the order for an
appropriate mach. The first handler that yields a match is executed. After executing the handler,
the control goes to the first statement after the last catch block for that try. When no match is
found the program will terminate.
It is possible that arguments of several catch statements match the type of exception. In
such cases, the first handler that matches the exception type is executed.
/*Write a C++ program to throw multiple exceptions and define multiple catch statement. */
#include <iostream> using namespace std;
void num (int k){
try{
if (k==0) throw k; else
elseif (k>0) throw 'P';
if (k<0) throw 1.0;cout<<"*** end of try block ***\n";
}catch(char g){
cout<<"Caught a positive value \n";}catch (int j){
cout<<"caught an null value \n";}catch (double f){
cout<<"Caught a Negative value \n";}cout<<"*** end of try catch ***\n \n";
}int main(){
cout<<"Demo of Multiple catches"<<endl; num(0);num(5);num(-1); return 0;
}Output:
Demo of Multiple catches caught an null value*** end of try catch *** Caught a positive value
*** end of try catch *** Caught a Negative value
*** end of try catch *** Caught a positive value*** end of try catch ***
Catching Multiple Exceptions
In some situations, we may not able to anticipate all possible types of exceptions and therefore
may not be able to design independent catch handlers to catch them. In such circumstances, we
can create a catch statement to catch all exceptions instead of a certain type alone.
Syntax:
catch(...){
// Statements for handling// all exceptions
}
/* Write a C++ program to catch multiple exceptions.*/
#include <iostream> using namespace std;
void num (int k){
try{
if (k==0) throw k; else
else
}
if (k>0) throw 'P';
if (k<0) throw 1.0;
catch(...){
cout<<"Caught an Exception"<<endl;}
}int main(){
cout<<"Demo of Multiple catches"<<endl; num(0);num(5);num(-1); return 0;
}
10
Output:Demo of Multiple catches Caught an Exception Caught an Exception Caught an Exception
Specifying Exceptions
It is possible to restrict a function to throw only certain specified exceptions. This is
achieved by adding a throw list clause to the function definition. The general form of using an
exception specification is:
return_type fucntion_name (parameter list) throw (data type list){
// function body}
The data type list indicates the type of exception that is permitted to be thrown. If we
want to deny a function from throwing any exception, declaring the data type list void as per the
following statement can do this.
throw(); // void or vacant list
/* Write a C++ program to restrict a function to throw only specified type of exceptions. */
#include<iostream> using namespace std;
void check (int k) throw (int){
if (k==1) throw 'k'; else
else
}
if (k==2) throw k;
if (k==-2) throw 1.0;
int main(){
try {check(1);check(-2);
11
check(3);}catch (char g){
cout<<"Caught a character exception \n";}catch (int j){
cout<<"Caught a character exception \n";}catch (double s){
cout<<"Caught a double exception \n";}cout<<"\n End of main()"; return 0;
}
C++ Files and Streams
We have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.
Then how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types
ofstream
This data type represents the output file stream and is used to create files and to write
information to file
ifstream
This data type represents the input file stream and is used to read information from files
fstream
This data type represents the file stream generally, and has the capabilities of both ofstream
and ifstream which means it can create files, write information to files, and read information
from files
12
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
ios::app
Append mode. All output to that file to be appended to the end.
ios::ate
Open a file for output and move the read/write control to the end of the file
ios::in
Open a file for reading.
ios::out
Open a file for writing
ios::trunc
If the file already exists, its contents will be truncated before opening the file.
13
You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory
and close all the opened files. But it is always a good practice that a programmer should close all the
opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream
objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion
operator (<<) just as you use that operator to output information to the screen. The only difference is that
you use an ofstream or fstream object instead of the cout object.
14
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use
that operator to input information from the keyboard. The only difference is that you use
an ifstreamor fstream object instead of the cin object.
Read and Write Example
Following is the C++ program which opens a file in reading and writing mode. After writing information
entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto
the screen –
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
15
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
16
TEMPLATES IN C++ Template is simple yet very powerfull tool in C++. Templates are the foundation of generic programming, which involves writing code in a way i.e.
independent of a particular type. Template is a blueprint or formula for creating a generic class or function. Template is of 2 types:-
o Function Templateo Class Template
Function Template:-
1. Function templates are special functions that can operate with generic types.2. This allows us to create a function template whose functionality can be adapted to more than
one tye or class without repeating the entire code for each type. 3. The simple idea is to pass data type as a parameter so that we don’t need to write same code
for different data types4. We write a generic function that can be used for different data types.
Function Overloading:-int add(int x,int y){}float add(float x,float y){}double add(double x,double y){}int main(){ add(5,4);add(2.3f,4.2f);add(5.3232,4324.126)}
*Function template:-template <typename T>T add(T x,T y){}int main{ add<int>(3,7);add<float>(3.3,7.5);add<double>(3.55,7.66);}
Example:-
#include<iostream>int add(int x,int y){return(x+y);}float add(float x,float y){return(x+y);}double add(double x,double y){return(x+y);}
17
Int main(){cout<<”addition of two integers”<<add(3,4);return 0;}Using Template:-
#include<iostream>template <typename T>T add(T x,T y){ return(x+y);}Int main(){Cout<<add<int>(3,4);Cout<<add<float>(3.4f,2.5f);Cout<<add<double>(3.45,4.23);return 0;}Using Two different data types:-#include<iostream>template <typename T,typename U>U add(T x,U y){ return(x+y);}Int main(){Cout<<add<double>(3.0,4.5);return 0;}O/p-7.5
Class Templates:-Sometimes we need a class implementation i.e. same for all classes oly the data type used are different.Normally we would need to create a different class for each data type or create different member variables and functions with single class.In class Template we write a class that can be used for different data types.
Class stack{Public:
Class stack{Public:
18
Int arr[5];Private:Push();Pop();}
Char arr[5];Private:Push();Pop();}
Example: #include<iostream>template <typename T>class weight{ private: T kg; public: void setData(T x) { Kg=x; }T getData() { return kg; } };int main(){ weight <int>obj;obj.setData(5);cout<<obj.getData(); weight <double>obj1;obj1.setData(4.56575) ;cout<<obj1.getData();return 0;} Assignment:- Write a class template to pass another a double data type in the above example.