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;
}

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...

Be a part of the DaniWeb community

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