开发者

c++ exceptions and program execution logic

开发者 https://www.devze.com 2022-12-29 02:30 出处:网络
I have been thru a few questions but did not find an answer. I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress?

I have been thru a few questions but did not find an answer.

I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress?

For example, I want to process exceptions at four s开发者_开发技巧tages of the program and know that exception happened at that specific stage:

1. Initialization

2. Script processing

3. Computation

4. Wrap-up.

At this point, I tried this:

int main (...)
{
...
// start logging system
try {
    ...
    }
catch (exception &e)
  {
        cerr << "Error: " << e.what() << endl;
        cerr << "Could not start the logging system. Application terminated!\n";
        return -1;
  }
catch(...)
    {
        cerr << "Unknown error occured.\n";
        cerr << "Could not start the logging system. Application terminated!\n";
        return -2;
    }

// open script file and acquire data
try {
...
    }
catch (exception &e)
  {
        cerr << "Error: " << e.what() << endl;
        cerr << "Could not acquire input parameters. Application terminated!\n";
        return -1;
  }
catch(...)
    {
        cerr << "Unknown error occured.\n";
        cerr << "Could not acquire input parameters. Application terminated!\n";
        return -2;
    }
// computation
try {
...
}
...

This is definitely not centralized and seems stupid. Or maybe it is not a good concept at all?


You could keep a global variable containing the state of the program, and print it out in the catch block. Then you would only need two catch blocks, one for std::exception and one for everything else.


It seems to me that you're trying to use exceptions as (more or less) a replacement for logging. I think in this case, you'd be a lot better off using the two together -- in particular, I'd probably have a small exception handler that put output in the log, so your code would look something like this:

try { 
    // start logging system
}
catch (exception const &e) { std::cerr << e.what << "error starting logging"; }
catch (...) { std::cerr << "Unknown error starting logging"; }

try { 
    {   scoped_log("script processing");
        start_script();
    }
    {   scoped_log("computation");
        do_computation();
    }
    {   scoped_log("wrap up");
        wrap_up();
    }
}
catch(std::exception const &e) { log << "error: " << e.what() << "\n"; } 
catch(...) { log << "Unknown exception\n"; }  

where "scoped_log" is a simple class something like:

class scoped_log { 
    std::string caption;
public: 
    scoped_log(std::string const &c) : caption(c) {
        log << "Starting:  " << caption << "\n";
    }
    ~scoped_log() { log << "Finished: " << caption << "\n"; }
};

This allows you to centralize most of the exception handling. The only exception (no pun intended) is for starting up the logging system itself -- you obviously can't use logging to report problems with starting up the logging system.

Once the logging system is up, however, things are a lot simpler -- you use the combination of logging and exception handling to track down when the problem occurred. Keep one minor detail in mind: since the scoped_log is an object that's destroyed when the scope is exited (for any reason), the log will have a structure that might (at least initially) seem a bit misleading -- the error message will follow the "finshed xxx" message in the log. For example, if a script file couldn't be opened, your log might look something like this:

starting script processing
finished script processing
error: could not open file: 'script.input'

At least IMO, that's unlikely to cause a problem if you're aware of the situation.


In my opinion, exceptions should be (generally) caught in 5 conditions:

  1. You can legitimately handle the exception and continue normally (e.g. you caught a boost::bad_lexical_cast from user input, but can recover by reporting the error to the user).
  2. You need to translate the exception from one source to another (e.g. your library uses another library as a pure implementation detail and wants to translate a 'socket_exception' into a 'service_exception' or something of the sort). In .Net, I'd do this by throwing a new exception instance w/ an inner exception. In C++, it can be useful to provide a consistent interface to your users, especially if you're, for instance, only throwing exceptions derived from std::exception, but a dependent library throws exceptions from a non-standard type (string, int, const char*, custom type, etc).
  3. You're writing a cross language wrapper. C++/C, C++/Fortran, etc. C++ exceptions don't tend to cross these barriers well, and you're best off translating them into the target runtime's error handling facilities, if possible.
  4. You're in main, and wish to capture some slight information from the exception & log before you crash. If you do so, there's two primary camps on what to do next: exit(1) or throw; and generate a core (on *nix). I've mixed feelings...
  5. much like in main, around a thread entry. Can be helpful to log why a thread terminated, and then treat thread termination in a appropriate manner.


A simple way of having exception processing centralized is creating a simple function to process the exceptions and then using a generic catch that calls the function:

void processExceptions( std::string const & stage )
{
   std::cout << "Exception caught at stage " << stage << std::endl;
   try {
      throw; // rethrow the last caught exception
   }
   catch ( exception1 const & ) { 
      // do process 1
   }
   catch ( exception2 const & ) {
      // ...
   }
}
int main()
{
   try {
      initialize();
   }
   catch ( ... ) {
      processExceptions( "initialization" );
   }
   try {
      stage2();
   }
   catch ( ... ) {
      processExceptions( "stage2" );
   }
}

I have never used that technique to identify when an exception was caught, but it is quite useful to avoid duplicating exception processing code in many places if it is the same.

Note that if you call the function when no exception has been thrown (outside of a catch) you will get undefined behavior and more often than not your application will die.


The other alternative is to have distinct, by-you-defined exceptions which you then handle in one central place instead of different return values. So when the exception occurs like "could not acquire input parameters" you would throw something like an "invalid_parameters exception" with some more context information added about the reason for the exception. Then in a central place you display the error.


If you really want to more centralize this, you could define your own error classes such as


class does_not_open {};  
class cannot_write {};

or so. You'll need more work in your different parts, e.g., check if open succeeds; if not, throw does_not_open (etc.). But after you organize yourself this way, you can put the entire main part of your code into the following form:


try{  


}  

catch(does_not_open &e){  


}

catch(cannot_write &e){

- your code here -

}
catch(...){

- your code here -

}

Not sure this accomplishes what you were hoping for...but gl. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号