title: Can exit() from a library be replaced with throwing an exception?
body: <p>I'm working with a C/Fortran library from C++ and the library calls exit(). I would like it to throw an exception so that the destructors in my C++ program will be called. I have been able to create my one definition of exit that throws an exception, but then terminate is still called. Is there to prevent terminate from being called and allow the normal exception handling to happen?</p>
  
  <p>UPDATE: In the comments it was pointed out that this works on x64 but fails on x86, so the main question is "is there is a way to make x86 work like x64?".</p>
  
  <p>UPDATE2: See my response about why this wasn't working on x86 and how to fix it.</p>
  
  <p>Here's my test code:</p>
  
  <p>test_exception.c</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  
  void call_c() { exit(1); }
  </code></pre>
  
  <p>test_exception.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdexcept&gt;
  
  extern "C" void call_c();
  
  extern "C" void exit(int value)
  {
    throw std::runtime_error(std::string("Throwing an exception: ") + char('0' + value));
  }
  
  int main()
  {
    try {
      call_c();
    } catch (const std::exception &amp;e) {
      std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;
      return 1;
    }
  
    return 0;
  }
  </code></pre>
  
  <p>Built with the following commands:</p>
  
  <pre><code>gcc -c test_exception.c -o test_exception_c.o
  g++ -c test_exception.cpp -o test_exception_cpp.o
  g++ test_exception_c.o test_exception_cpp.o -o test_exception
  </code></pre>