Basics of Exception Handling
Exceptions are of two kinds, namely, synchronous exceptions and
asynchronous exceptions. Errors such as "out-of-range index" and
"over-flow" belong to the synchronous type exceptions. The errors
that are caused by events beyond the control of the program (such
as keyboard interrupts) are called asynchronous exceptions. The
proposed exception handling mechanism in C++ is designed to
handle only synchronous exceptions.
The purpose of the exception handling mechanism is to provide
means to detect and report an "exceptional circumstance" so that
appropriate action can be taken. The mechanism suggests a
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).
4. Take corrective actions (Handle the exception).
The error handling code basically consists of two segments, one to
detect errors and to throw exceptions, and the other to catch the
exceptions and to take appropriate actions.
Exception Handling Mechanism
C++ exception handling mechanism is basically built upon three
keywords, namely, try, throw, and catch. The keyword try is used to
preface a block of statements (surrounded by braces) which may
generate exceptions. This block of statements is known as try block.
When an exception is detected, it is thrown using a throw statement
in the try block. A catch block defined by the keyword catch
'catches' the exception 'thrown' by the throw statement in the try
block, and handles it appropriately. The relationship is shown in Fig.
13.1.
The catch block that catches an exception must immediately follow
the try block that throws the exception. The general form of these
two blocks are as follows:
13.4 Throwing Mechanism
When an exception that is desired to be handled is detected, it is
thrown using the throw statement in one of the following forms:
throw(exception);
throw exception;
throw: // used for rethrowing an exception
The operand object exception may be of any type, including
constants. It is also possible te throw objects not intended for error
handling.
When an exception is thrown, it will be caught by the catch
statement associated with the try block. That is, the control exits the
current try block, and is transferred to the catch block after that try
block, 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.
13.5 Catching Mechanism
As stated earlier, code for handling exceptions is included in catch
blocks. A catch block looks like a function definition and is of the
form
catch(type arg)
{
// Statements for
// managing exceptions
}
The type indicates the type ofrexception that catch block handles.
The parameter arg is an optional parameter name. Note that the
exception-handling code is placed between two
The catch statement catches an exception whose type matches
with the type of ratch argument. When it is caught, the code in the
catch block is exeented .If the parameter in the catch statement is
named, then the parameter can be used in the steption-handling
code. After executing the handler, the control goes to the statement
inmediately following the catch block.
Due to mismatch, if an exception is not caught, abnormal program
termination will occur. It is important to note that the catch block is
simply skipped if the catch statement does not catch an exception.
Multiple Catch Statements
It is possible that a program segment has more than one condition
to throw an exception. In such cases, we can associate more than
one eatch statement with a try (much like the conditions in a switch
statement) as shown below:
try
{
//try block
}
catch(typel arg)
{
//catch block1
}
catch (type2 arg)
{
//catch block2
}
catch(typeN arg)
{
//catch blockN
}
13.6 Rethrowing an Exception
A handler may decide to rethrow the exception caught without
processing it. In such situations, we may simply invoke throw
without any arguments as shown below:
Throws;
This causes the current exception to be thrown to the next enclosing
try/catch sequence and is caught by a catch statement listed after
that enclosing try block. Program 13.5 demonstrates how an
exception is rethrown and caught.
RETHROWING AN EXCEPTION
#include <iostream>
using namespace std;
void divide(double x, double y)
{
. cout << "Inside function \n";
try
{
if(y= 0.0)
throw y; // Throwing double
else
cout << "Division=”<< x/y<<"\n";
}
catch(double) //Catch a double
cout< "Caught double inside function \n";
throw; // Rethrowing double
}
cout << "End of function \n\n";
}
Int main()
{
cout "Inside main in";
try
{
divide(10.5,2.0);
divide (20.0.0.0);
}
catch(double)
{
cout << "Caught double inside main \n":
}
cout << "End of main \n";
return 0;
}
The output of the Program 13.5:
Inside main
Inside function
Division 5.25
End of function
Inside function
Caught double inside function
Caught double inside main
End of main
13.7 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:
type function(arg-list) throw (type-list)
{
…………
.………. Function body
}
The type-list specifies the type of exceptions that may be thrown.
Throwing any other type of exception will cause abnormal program
termination. If we wish to prevent a function jom throwing any
exception, we may do so by making the type-list empty. That is, we
must use
throw(); // Empty list
in the function header line.
Templates is one of the features added to C++ recently. It is a new
concept which enable us to define generic classes and functions
and thus provides support for generic programming. Generic
programming is an approach where generic types are used as
parameters in algorithms so that they work for a variety of suitable
data types and data structures.
A template can be used to create a family of classes or functions.
For example, a class template for an array class would enable us to
create arrays of various data types such as int array and float array.
Similarly, we can define a template for a function, say mul(), that
would help us create various versions of mul() for multiplying int,
float and double type values.
A template can be considered as a kind of macro. When an object of
a specific type is defined for actual use, the template definition for
that class is substituted with the required data type. Since a
template is defined with a parameter that would be replaced by a
specified data type at the time of actual use of the class or function,
the templates are sometimes called parameterized classes or
functions.
Class template
The class template definition is very similar to an ordinary class
definition except the prefix template<class T> and the use of
type T. This prefix tells the compiler that we are going to declare
a template and use T as a type name in the declaration. Thus,
vertor has become a parameterized class with the type Tas its
parameter. T may be substituted has become type including the
user-defined types. Now, we can create vectors for holding
different data types.
Example:
vector<int> v1 (10); // 10 element int vector
vector <float> v2(25); // 25 element float vector
The type T may represent a class name as well. Example:
vector <complex v3(5); // vector of 5 complex numbers
A class created from a class template is called a template class.
The syntax for defining object of a template class is:
classname<type> objectname(anglist);
EXAMPLE OF CLASS TEMPLATE
#include <iostream>
using namespace std;
const size = 3;
template <class T>
class vector {
T* v; // type T vector
public:
vector() {
v = new T[size];
for (int i = 0; i < size; i++)
v[i] = 0;
}
vector(T* a) {
for (int i = 0; i < size; i++)
v[i] = a[i];
}
T operator*(vector& y) {
T sum = 0;
for (int i = 0; i < size; i++)
sum += this->v[i] * y.v[i];
return sum;
}
};
int main() {
float x[3] = {1.1, 2.2, 3.3};
float y[3] = {4.4, 5.5, 6.6};
vector<float> v1;
vector<float> v2;
v1 = x;
v2 = y;
float R = v1 * v2;
cout << "R = " << R << "\n";
return 0;
}
Output
R = 38.720001
Function Templates:- Like class templates, we can also define
function templates that could be used to create a family of
functions with different argument types. The general format of a
function template is
template class T>
returntype functioname (arguments of type T)
{
//…..
// Body of function
// with type
// wherever appropriate
}
The function template syntax is similar to that of the class
template except that we are defining functions instead of
classes. We must use the template parameter T as and when
necessary in the function body and in its argument list.
The following example declares a swap() function template that
will swap two values of a given type of data.
template class T
void swap (T and x, T and y)
{
T terp = x;
X = y;
Y = temp;
}
This essentially declares a set of overloaded functions, one for
each type of data, We can invoke the swap) function like any
ordinary function. For example, we can apply the swap) function
as follows:
Example of function template
vold f(int m.int in,float a,float b)
{
swap(m,n); // swap two integer values
swap(a,b); // swap two float
#include <iostream>
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) {
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
Object-Oriented Programming (OOP) Concepts
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects," which can contain data (attributes) and code (methods). OOP focuses on the
organization of code into reusable units called classes and objects, which provide a natural way
to model real-world entities.
Comparison Between Procedural Programming and Object-Oriented Programming
Procedural Object-Oriented
Aspect Programming Programming
Focuses on
functions Focuses on objects
(procedures) and and their
Approach their execution. interactions.
Code is organized Code is organized
into functions or into classes and
Modularity modules. objects.
Data and Data and functions
functions are are encapsulated
Data separate. within objects.
Limited
reusability, High reusability
functions must be through inheritance
Reusability rewritten. and polymorphism.
Easier to manage
Difficult to complexity using
Complexity manage large- abstraction and
Management scale programs. encapsulation.
Examples C, Pascal C++, Java, Python
Basic Concepts of Object-Oriented Programming
1. Object and Class
• Object: An object is a real-world entity or an instance of a class. It contains
attributes (data) and methods (functions).
• Class: A class is a blueprint for creating objects. It defines the properties and
behavior that its objects will have.
2. Interface and Implementation of a Class
• Interface: Specifies the public methods and attributes of a class, which can
be accessed by other classes or objects.
• Implementation: Refers to the actual code and logic behind the methods
and attributes.
3. Operations on Objects
Operations include creating, modifying, and interacting with objects using methods.
Example: Assigning values, invoking methods, and destroying objects.
4. Relationship Among Objects
• Association: A relationship where objects are associated but independent.
• Aggregation: A "has-a" relationship; objects are part of a whole but can exist
independently.
• Composition: A stronger form of aggregation where the parts cannot exist
independently of the whole.
• Inheritance: A "is-a" relationship; objects inherit properties and methods
from parent classes.
5. Abstraction
Abstraction hides the internal details of an object and exposes only the essential features.
Example: A car exposes its functionality (drive) but hides the engine's internal workings.
6. Encapsulation
Encapsulation bundles data and methods within a class, restricting direct access. This is
achieved using access specifiers like private, protected, and public.
7. Data Hiding
A part of encapsulation, data hiding ensures that internal object details are not accessible
directly, enhancing security.
8. Inheritance
Allows a class to inherit properties and behavior from another class. Types include:
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
9. Overloading
• Function Overloading: Same function name with different parameter types
or counts.
• Operator Overloading: Extending the functionality of operators for user-
defined data types.
10. Polymorphism
Polymorphism allows a single function or operator to behave differently based on the
context.
• Compile-time Polymorphism: Achieved through overloading.
•Runtime Polymorphism: Achieved through function overriding using virtual
functions.
11. Messaging
Objects communicate with each other by sending messages (invoking methods).
Classes and Objects
1. Specifying a Class
A class is defined using the class keyword. Example:
cpp
Copy code
class Rectangle { int length, breadth; public : void setDimensions(int l, int b) { length = l; breadth =
b; } int area() { return length * breadth; } };
2. Creating Class Objects
Objects are created using the class name. Example:
cpp
Copy code
Rectangle rect1, rect2;
3. Accessing Class Members
Use the dot operator to access members. Example:
cpp
Copy code
rect1. setDimensions ( 5 , 10 ); int area = rect1. area ();
4. Access Specifiers
• public: Members are accessible from outside the class.
• private: Members are accessible only within the class.
• protected: Members are accessible within the class and its derived classes.
5. Static Members
Shared across all objects of a class. Example:
cpp
Copy code
class Counter { static int count; public : Counter () { count++; } static int getCount() { return
count; } }; int Counter::count = 0 ;
6. Use of const Keyword
Used to make variables, methods, or objects constant. Example:
cpp
Copy code
const int x = 10 ; void print() const ;
7. Friends of a Class
A friend function or class can access private and protected members of another class.
Example:
cpp
Copy code
class A { friend void show(A obj) ; private : int data; };
8. Empty Classes
Classes with no data members or member functions. Example:
cpp
Copy code
class Empty {};
9. Nested Classes
Classes defined within another class. Example:
cpp
Copy code
class Outer { class Inner {}; };
10. Local Classes
Classes defined within a function. Example:
cpp
Copy code
void func() { class Local {}; }
11. Abstract Classes
Classes with at least one pure virtual function. Example:
cpp
Copy code
class Abstract { virtual void display() = 0 ; };
12. Container Classes
Classes used to hold and manage objects. Example: Standard Template Library (STL) in
C++.
13. Bit Fields and Classes
Used to optimize memory usage by storing small amounts of data. Example:
cpp
Copy code
class Flags { unsigned int a : 1 ; unsigned int b : 1 ; };