0

Hi,

I'm just starting to practice with c++ and I'd like to know if there is a good way to handle the errors/exception.

I write this program to check the modification time of a file.

Thanks

int filewatcher::watch()
{
    struct stat filestatus;
    stat(this->_filename, &filestatus);

    if((filestatus.st_mode & S_IFMT) == S_IFREG)
    {
        time_t m_time_old = filestatus.st_mtime;

        int i = 0;
        while(i < this->_timestowatch)
        {
            try
            {
                stat(this->_filename, &filestatus);

                if(m_time_old != filestatus.st_mtime)
                {
                    m_time_old = filestatus.st_mtime;
                    cout << "it has changed !!!" << endl;
                }
                else
                {
                    cout << "there is NO change." << endl;
                }
            }
            catch(runtime_error e)
            {
                log_error(e);

                return -2;
            }
            catch(...)
            {
                log_unknow_error("error no previst");

                return -1;
            }

            printf("%d seconds waiting %c %c", i * 5, '\n', '\n');
            i++;
            sleep(5);
        }
    }
    else
    {
      printf("%s %s", this->_filename, " is not a regular file");

      return -3;
    }

    return 0;
}

void log_unknow_error(string error)
{
    cout << "an error has ocurred : " << error << endl;
}

void log_error(runtime_error e)
{
    cout << "an error has ocurred : " << e.what() << endl;
}
2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Nick Evan
0

You're using try and catch, so that's a good thing. How and where you throw and catch is also a matter of personal taste.
Some people (like me) try a small piece of code and catch if something goes wrong. Some other people just wack their code in one big try() and catch if anything fails...

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.