C & C++ Programming - Exception Handling
#include "stdafx.h"
#include < stdio.h >
#include < stdlib.h >
enum ERROR
{
FILENOTFOUND = 1,
MEMORYNOTALOCATED,
UNDEFINED
};
//////////////////////////////////////////////////////////////////////////////////////////////////
// I Method - Catch should be define in constructor itself
class A
{
public:
A(char *FileName, int cnt)
{
try
{
fp = fopen( FileName, "r" );
if(!fp) throw FILENOTFOUND;
str = (char *) malloc(cnt*sizeof(cnt));
if(!str) throw MEMORYNOTALOCATED;
}
catch(ERROR e)
{
switch(e)
{
case FILENOTFOUND:
printf("File not found\n");
break;
case MEMORYNOTALOCATED:
printf("File not found\n");
break;
default:
printf("Undefined Error\n");
break;
}
}
}
~A()
{
cout << "DTOR\n";
}
private:
FILE *fp;
char *str;
};
main()
{
A obj("Vector.hxx", 20);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// II Methodlogy - evil destructor will not call.
class A
{
public:
A(char *FileName, int cnt)
{
fp = fopen( FileName, "r" );
if(!fp) throw FILENOTFOUND;
str = (char *) malloc(cnt*sizeof(cnt));
if(!str) throw MEMORYNOTALOCATED;
}
~A()
{
cout << "DTOR\n";
}
private:
FILE *fp;
char *str;
};
//////////////////////////////////////////////////////////////////////////////////////////////////
void TestException()
{
try
{
A obj("Vector.hxx", 20);
}
catch(ERROR e)
{
switch(e)
{
case FILENOTFOUND:
printf("File not found");
break;
case MEMORYNOTALOCATED:
printf("File not found");
break;
default:
printf("Undefined Error");
break;
}
}
}