Greeting guys

Rookie here again. By the way, thanks for all the help. Anyway to business. I am trying to compile a program to understand how to handle exceptions using inheritance. I have created first error.h where all the classes and child classes are defined. Then when I create my main code and try to compile it it gives me an error on the following part

throw de;

Any idea why. Thank you once again for the help

This is the error.h file

#include <fstream>
#include <memory>
#include <iostream>
using namespace std;  
class error
 fstream errfile;
 void printmsg(char *msg);
 void logmsg(char *msg);
void error::printmsg(char *msg)
 cout << msg;
void error::logmsg(char *msg)
 errfile << msg;
class fileerror:public error
   class divisionbyzero:public error

And this is the program

#include "error.h"
#include <iostream>
using namespace std;
fileerror fe;
divisionbyzero de;
int main()
     fstream f;
     float dividend, divisor,quotient;
 cout << "Enter a number " << endl;
     cin >> dividend;
     cout << "Enter another number " << endl;
     cin >> divisor;
     // if the divisor is zero we should
     // get the divisionbyzero
     throw de;
     quotient = dividend/divisor;
     cout << quotient;
     // if there is no file then we should get
     // the fileerror"somefile.txt",ios::in);
     throw fe;
catch(divisionbyzero d)
d.printmsg("Division by zero \n");
catch(fileerror f)
f.printmsg("File not found error \n");
cout<< "Unknown error! \n";
     return 0;

Recommended Answers

All 2 Replies

After a little testing it appears that the c++ doesn't support fstream in that error class when used in a throw statement. Comment out the fstream object and it the program compiles ok. I'm not enough of an expert in this to tell you why that is happening.


throw [B]expression[/B] ;

a. the (static) type of expression cannot be an incomplete type.
b. the static type of the expression is used to initialize a temporary object of that type (through the type's copy-constructor) into a special memory location which must stay valid during the subsequent stack unwinding. (the memory location used is completely implementation-dependent.) this temporary object is destroyed (its destructor is invoked and then its memory freed) when the stack unwinding completes.
c. the C++ specification suggests that the expression can be viewed in the same way as an argument to a function call (passed by value). therefore, if the expression is an object, the copy constructor and destructor of that object must be accessible.

c++ stream objects are not copyable; so the class error (which contains a stream object) is also not copyable. and the derived classes fileerror and divisionbyzero are also not copyable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.