Can exit() from a library be replaced with throwing an exception?
This question already has an answer here:
I understand you may not want to read this, but it's most likely a mistake to continue executing a program after any part of it has attempted to call exit()
or similar.
If part of the program called exit()
, you have no guarantees about the state of the program at that point. You don't know if the heap is in a consistent state. You don't know if the stack is any good. If you convert the exit()
into a throw
, the very least you're likely to encounter are memory leaks each time this happens. You don't know if the library that caused this error can be safely called again.
If you have inspected the library's source code, and you're certain that no corruption will result, then the cleanest solution would be to modify the library itself, so that it throws instead of exiting.
If changing the library is not permissible, the other clean and correct solution is to put all usage of the library into a separate process which you can monitor and restart.
The above code works, but on x86 before gcc 4.6, -fexceptions or -funwind-tables needs to be added when building the C code so that the stack unwinding can happen. You can see the details here.
Unless your C++ implementation is broken, it will call destructors for global variables when exit
is called (GCC is not broken, as least all the versions I've tried). So you only need to clean up stuff that won't be cleaned up by destructors of global vars.
For global stuff on the heap, you can use atexit
to register a cleanup function that will be called when exit
is called -- this cleanup function can delete
any heap objects that need to be cleaned up.
Destructors for stuff on the stack is much trickier. The best solution is probably to ensure that such destructors don't need to be called -- anything that MUST be cleaned up before exit should be referred to by a global (possibly using static members of classes) that does the cleanup in its destructor.
链接地址: http://www.djcxy.com/p/26124.html上一篇: JavaFX 8对话框内部元素的本地化
下一篇: 从库中退出()可以被抛出异常替换?