5

I am trying to load a dynamic library using dlopen function. This library contains a static object, which throws an exception in its constructor. I have a "try-catch(...)" block around the dlopen call, but it doesn't catch the exception, and I just see "Abort" printed.

How am I able to catch this exception?

Igor
  • 26,650
  • 27
  • 89
  • 114

1 Answers1

6

Short Answer: You Can't

Thinking about it again.
The original statements holds, but you must also remember that dlopen() is a C library function. C does not support exceptions. Thus throwing an exception that crosses from C++ code to C ( Your global object back upto dlopen() ) code will also cause application termination.

See here:Why destructor is not called on exception?

These are the situations under which throwing an exception will terminate the application. Your specific situation is covered by:

An exception escapes the constructor/destructor of a non local static (ie global)

Community
  • 1
  • 1
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • And the obvious corollaries: (1) Global variables, um..ahem.. "singletons" are bad. mkay? (2) throwing an exception from a constructor of an object intended to be used as a singleton is even worse. (3) library code should never do anything that can cause the calling program to abort unless a contract has been broken (like passing an invalid pointer. – R.. GitHub STOP HELPING ICE Feb 06 '12 at 16:36
  • @R..: Totally agree. I don't think we need to drag singletons into this. The phrase we are looking for is `globally accessible -->mutable<-- state` whose construction can cause exceptions outside the confines of main() (or just by being loaded) are not a good idea (singletons just happen to be a subset of this larger class). Note: I suppose immutable state can also cause a problem if we want to be pedantic but usually its less worrisome. – Martin York Feb 06 '12 at 18:46
  • If it's truly immutable, I wouldn't call it a "state". But in my book, any object with a constructor that modifies its contents is "mutable" even if there are no methods to later change it after construction. – R.. GitHub STOP HELPING ICE Feb 06 '12 at 19:07