Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

前端 未结 16 1631
情深已故
情深已故 2020-11-22 17:15

Does C++ support \'finally\' blocks?

What is the RAII idiom?

What is the difference between C++\'s RAII idiom and C#\'s \'using\' statement?

16条回答
  •  天命终不由人
    2020-11-22 17:42

    Not really, but you can emulate them to some extend, for example:

    int * array = new int[10000000];
    try {
      // Some code that can throw exceptions
      // ...
      throw std::exception();
      // ...
    } catch (...) {
      // The finally-block (if an exception is thrown)
      delete[] array;
      // re-throw the exception.
      throw; 
    }
    // The finally-block (if no exception was thrown)
    delete[] array;
    

    Note that the finally-block might itself throw an exception before the original exception is re-thrown, thereby discarding the original exception. This is the exact same behavior as in a Java finally-block. Also, you cannot use return inside the try&catch blocks.

提交回复
热议问题