Thursday 10 November 2016

How to generate exceptions in virtual constructors

It is possible that exceptions might raise in a constructor or destructors. If an exception is raised in a constructor, memory might be allocated to some data members and might not be allocated for others. This might lead to memory leakage problem as the program stops and the memory for data members stays alive in the RAM.

 

Similarly, when an exception is raised in a destructor, memory might not be deallocated which may again lead to memory leakage problem. So, it is better to provide exception handling within the constructor and destructor to avoid such problems. Following program demonstrates handling exceptions in a constructor and destructor:

#include<iostream>

using namespace std;

class Divide

{

private:

int *x;

int *y;

public:

Divide()

{

x = new int();

y = new int();

cout<<“Enter two numbers: “;

cin>>*x>>*y;

try

{

if(*y == 0)

{

throw *x;

}

}

catch(int)

{

delete x;

delete y;

cout<<“Second number cannot be zero!”<<endl;

throw;

}

}

~Divide()

{

try

{

delete x;

delete y;

}

catch(...)

{

cout<<“Error while deallocating memory”<<endl;

}

}

float division()

{

return (float)*x / *y;

}

};

int main()

{

try

{

Divide d;

float res = d.division();

cout<<“Result of division is: “<<res;

}

catch(...)

{

cout<<“Unkown exception!”<<endl;

}

return 0;

}

Input and output for the above program is asfollows:

Enter two numbers: 5 0

Second number cannot be zero!

Unkown exception!

 

Advantages of Exception Handling

 

Following are the advantages of exception handling:

Exception handling helps programmers to create reliable systems.Exception handling separates the exception handling code from the main logic of program.Exceptions can be handled outside of the regular code by throwing the exceptions from a function definition or by re-throwing an exception.Functions can handle only the exceptions they choose i.e., a function can throw many exceptions, but may choose handle only some of them.

A program with exception handling will not stop abruptly. It terminates gracefully by giving appropriate message.

Take you time to comment on this article.

No comments:

Post a Comment