title: How to avoid crashing while calling function throwing exception from .so
body: <p>Here is what I did, I want to gracefully handle this exception:</p>
  
  <p>code_snippet: my.cpp</p>
  
  <pre><code>#include&lt;iostream&gt;
  extern "C" void some_func()
  {
      throw "(Exception Thrown by some_func!!)";
  }
  </code></pre>
  
  <p>code_snippet: exception.c</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  extern void some_func();
  int so_main()
  {
      some_func();
      return 0;
  }
  </code></pre>
  
  <p>From above two snippets I have created a shared_object libexception.so by using following commands:</p>
  
  <pre><code>g++ -c -fPIC src/my.cpp
  gcc -c -ansi -fPIC src/exception.c
  g++ -fPIC -shared -o libexception.so
  </code></pre>
  
  <p>Then I called the function so_main from my main.cpp
  code_snippet: main.cpp</p>
  
  <pre><code>#include&lt;iostream&gt;
  #include &lt;dlfcn.h&gt;
  using namespace std;
  extern "C" void some_func();
  int main()
  {
      int (*fptr)() = 0;
      void *lib = dlopen("./libexception.so", RTLD_LAZY);
      if (lib) {
          *(void **)(&amp;fptr) = dlsym(lib, "so_main");
          try{
             if(fptr) (*fptr)();    &lt;-- problem lies here
             //some_func();        &lt;-- calling this directly won't crash
          }
          catch (char const* exception) {
              cout&lt;&lt;"Caught exception :"&lt;&lt;exception&lt;&lt;endl;
          }
      }
  return 0;
  </code></pre>
  
  <p>}</p>
  
  <p>final command: g++ -g -ldl -o main.exe src/main.cpp -L lib/ -lexception</p>
  
  <p>Executing main.exe crashes. Can somebody help me detect where the problem lies and how to avoid this crash to happen (We have already some architecture where some .SO calls extern c++ function, so that can't be changed, We want to handle it in main.cpp only)</p>