some problems about c++ try catch [closed]

Exceptions are brutal break of the normal flow of execution. The error correcting flow is to find a catch that correspond to the object thrown; this may lead to several function calls reverse traversal. This is why it needs care to use them, you have two flow of execution : the normal one, and the error one.

If the exception thrown is catched by the catch-block directly after, then you just have to set your variable to 0 in the catch-block.

It not, a good solution is RAII (as suggested in comments). RAII is a very simple idea. As you know that every object created on stack at the entry of any block is destroyed when control leave the block, the idea is to build an object that encapsulate something, so that the destructor will be called whatever happens:

class GlobalControl {
  public:
    GlobalControl() { myglob = 1; } // RAII
    ~GlobalControl() { myglob = 0; } // RRID
};

... // somewhere else
try {
  GlobalControl c; // ctor call init glob to 1
  ...
} // whatever will happens, leaving this block cause a call to dtor of c
catch (...) {
}

RAII stands for Resource Acquisition Is Initialization, here your resource acquisition is to set your global to 1, and this is made in the initialization part of the object. RAII should be called RAIIRRID, RAII + Resource Releasing Is Destruction (the resource release is to set your global to 0, and this is made in the destructor).

Leave a Comment