This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: try-catch block


On Tue, Aug 27, 2002 at 10:16:18AM +0200, Andrew Snare wrote:
> At 10:56 AM 27/08/2002 +0300, Serguei I. Ivantsov wrote:
> >Hi!
> >
> >Please help me to port this code to Linux from M$ (c++)
> 
> This sort of question is a general C++ question, and probably not best sent 
> to this list.
> 
> >//...
> >try{
> >lock_semaphore();
> >something_terrible_function();  // can produce any kind of exception
> >unlock_semaphore();
> >}catch(...){
> >unlock_semaphore();
> >};
> >// ...
> >It is important that process must continue execution and unlock semaphore
> >after any exception in something_terrible_function()
> 
> The code-snippet that you pasted will work, although the exception that 
> occurs is not propagated. This sort of thing is best handled using the 
> 'initialization-is-acquistion' pattern described by Stroustrup (14.4 
> Resource Management).
...

This is the same guy who was asking about how to treat signals as
exceptions, yesterday.  That's a harder question, and at least
partially on topic for this list.

I believe that this fragment suffices to do that:

#include <csignal>

struct SignalAsException {
  int signo;
  SignalAsException(int s) : signo(s) {};
};

void handler(int signo) {
  throw new SignalAsException(signo);
}

void setup_signals(void) /* called from main */
{
  std::signal(SIGHUP, handler);
  std::signal(SIGINT, handler);
  std::signal(SIGILL, handler);
  std::signal(SIGBUS, handler);
  std::signal(SIGFPE, handler);
  std::signal(SIGSEGV, handler);
}

provided that the entire program, and all libraries it links, are
compiled with -fnon-call-exceptions.  (In production code I would use
sigaction and take care that the handler didn't leave signals blocked,
but that would unnecessarily complicate this example.)  Depending on
what the program does, the list of signals to handle may need to be
adjusted.

zw


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]