Loading....
Coupon Accepted Successfully!

 

Exceptions In Constructors And Destructors

A copy constructor is called in exception handling when an exception is thrown fro the try block using the throw statement. The copy constructor mechanism is applied to initialize the temporary object. In addition, destructors are also executed to destroy the object. If an exception is thrown from the constructor, destructors are called only for those objects that are completely constructed.

19.7 Write a program to use exception handling with constructor and destructor.

#include<iostream.h>

#include<process.h>

class number

{

float x;

public :

number (float);

number() {};

~number()

{

cout<<“\n In destructor”;

}

void operator ++ (int) // postfix notation

{ x++; }

void operator --() // prefix notation

{

--x; }

void show()

{

cout<<“\n x=”<<x;

}

};

number :: number ( float k)

{

if (k==0)

throw number();

else

x=k;

}

void main()

{

try

{

number N(2.4);

cout<<“\n Before Increasing:”;

N.show();

cout<<“\n After Increasing:”;

N++; // postfix increment

N.show();

cout<<“\n After Decrementation:”;

--N; // prefix decrement

N.show();

number N1(0);

}

catch (number)

{

cout<<“\n invalid number”;

exit(1);

}

}

OUTPUT

Before Increasing:

x=2.4

After Increasing:

x=3.4

After Decrementation:

x=2.4

In destructor

In destructor

invalid number

Explanation: In the above program, the operators ++ and – are overloaded. The class number() has two constructors and one destructor. The one-argument constructor is used to initialize the data member x with the value given by the user. The overloaded operators are used to increase and decrease the value of the object. When the user specifies the zero value, an exception is thrown from the constructor. The exception is caught by the catch statement. In function()main(), two objects N and N1 are declared. The exception is thrown when the object N1 is created. When the exception is thrown, the control goes catch block. The catch block terminates the program. The destructors are also invoked.





Test Your Skills Now!
Take a Quiz now
Reviewer Name