0

Hi. I am wondering if a log file can be created in a header which is associated with a try-catch block. Below is my stripped down code for the log_header.h and log_test.cpp

Here is log_header.h

#include<fstream>
#include<iostream>
using namespace std;

class thrower{
    fstream myfile2;
public:
    void errormessage();
};

void thrower::errormessage(){
    cout<<"Thrower works\n";
    ///////These are log commnands////////
    myfile2.open("C:\\error2.txt",ios::out);
    myfile2<<"Message 2\n"<<endl;
    myfile2.close();
    ////////////////////////////////////////
};

Here is log_test.cpp

#include"log_header.h"
#include<fstream>

#include<iostream>
using namespace std;

thrower t;
int main(){

    fstream myfile;

    try{
        int y=4;
        if (y<5){
            throw t;
        }
    }
    catch(thrower tt){
        tt.errormessage();
        myfile.open("C:\\error.txt",ios::out);
        myfile<<"Message \n"<<endl;
        myfile.close();
    }
    return 0;
}   

If I comment out all of the log_header.h lines that contain "myfile2", then the "myfile" object in the log_test.cpp gets updated and the error message from the errormessage method is printed. It would be more elegant if the log file creation was contained in the header. Please assist.

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by JorgeM
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.