Data Abstraction

OO features of C++

Exception handling

#include <iostream.h>

class divide_by_zero {};

double avg(double a[], int size)

{

int sum=0;

for(int i = 0; i < size; i++)

sum += a[i];

if(size) return sum/size;

throw divide_by_zero();

}

void main()

{

try

{

double y[5];

y[0]=17.89;y[1]=10.9;y[2]=3.89;y[3]=1.40;y[4]=8.66;

avg(y,0);

}catch(divide_by_zero)

{

cerr << "Trying to divide by zero";

}

}

include <iostream.h>

enum illegal_operation {divide_by_zero, invalid_pointer};

double avg(double a[], int size)

{

int sum;

if(a == 0) throw invalid_pointer;

for(int i = 0; i < size; i++)

sum += a[i];

if(size) return sum/size;

throw divide_by_zero;

}

void main()

{

try

{

double y[5];

y[0]=17.89;y[1]=10.9;y[2]=3.89;y[3]=1.40;y[4]=8.66;

avg(0,10);

avg(y,0);

}catch(illegal_operation i)

{

switch(i)

{

case divide_by_zero:

cerr << "Trying to divide by zero";

break;

case invalid_pointer:

cerr << "Trying to dereference invalid pointer\n";

}

}

}

#include <iostream.h>

class illegal_operation {};

class divide_by_zero:public illegal_operation{};

class invalid_pointer:public illegal_operation{};

double avg(double a[], int size)

{

int sum;

if(a == 0) throw invalid_pointer();

for(int i = 0; i < size; i++)

sum += a[i];

if(size) return sum/size;

throw divide_by_zero();

}

void main()

{

try

{

double y[5];

y[0]=17.89;y[1]=10.9;y[2]=3.89;y[3]=1.40;y[4]=8.66;

//avg(0,10);

avg(y,0);

}catch( illegal_operation)

{

cerr << "Trying to do something illegal";

}

catch (invalid_pointer)

{

cerr << "Illegal pointer\n";

}

catch(divide_by_zero)

{

cerr << "Divide by zero\n";

}

}

#include <iostream.h>

struct illegal_operation

{

virtual void debug_print() { cerr << "Illegal Operation\n";}

};

struct divide_by_zero:public illegal_operation

{

void debug_print() { cerr << "Divide by zero\n";}

};

struct invalid_pointer:public illegal_operation

{

void debug_print() { cerr << "Invalid pointer\n";}

};

double avg(double a[], int size)

{

int sum;

if(a == 0) throw invalid_pointer();

for(int i = 0; i < size; i++)

sum += a[i];

if(size) return sum/size;

throw divide_by_zero();

}

void main()

{

try

{

double y[5];

y[0]=17.89;y[1]=10.9;y[2]=3.89;y[3]=1.40;y[4]=8.66;

//avg(0,10);

avg(y,0);

}catch( illegal_operation& i)

{

i.debug_print();

}

}

#include <iostream.h>

double avg(double a[], int size)

{

int sum;

if(a == 0) throw "invalid_pointer";

for(int i = 0; i < size; i++)

sum += a[i];

if(size) return sum/size;

throw "divide_by_zero";

}

void main()

{

try

{

double y[5];

y[0]=17.89;y[1]=10.9;y[2]=3.89;y[3]=1.40;y[4]=8.66;

//avg(0,10);

avg(y,0);

}catch( char i[])

{

cerr << i << endl;

}

}

Concluding remarks