- The Importance of Handling Exceptions
- A C++ Exception with No Handler
- A C++ Exception in a Call from Python
- Conclusion
- References
A C++ Exception in a Call from Python
Now suppose we want to see what happens if a C++ program throws an exception during its invocation from Python. To demonstrate this example in Listing 11, let's reuse the C++ code from Listing 8 and run it from Python. How do we run this C++ program from Python? Just as I describe in my article "Protect C++ Legacy Programs by Using Python," this goal is easily achieved with the Python script illustrated in Listing 11.
Listing 11A C++ Program with No Exception Handler, Called from Python.
import os, errno import subprocess as sp def invokeProgram(): try: print('Just before Python program invocation') p = sp.Popen(['/home/stephen/ExceptionManagement'], stdout = sp.PIPE) result = p.communicate()[0] print('ExceptionManagement program invoked: ') print('ExceptionManagement result: ' + result + os.linesep) except OSError as e: print('Exception handler error occurred: ' + str(e.errno) + os.linesep) if __name__ == '__main__': invokeProgram()
In Listing 11, the C++ program ExceptionManagement is invoked from Python using the subprocess module. To achieve this goal, just build the C++ binary file and copy it into the appropriate path on your system. I'm running the C++ program without its exception handler, so the main function looks like this:
int main () { callADynamicAllocationNoExceptionHandler(); return 0; }
Listing 12 shows the combined Python and C++ program output.
Listing 12The Python and C++ program output from an unhandled C++ exception.
Just before Python program invocation terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc ExceptionManagement program invoked: ExceptionManagement result:
The result in Listing 12 isn't too pretty. We get dumped out of the program as before, with no opportunity to clean up. Now let's rerun the Python code, using the C++ code that contains an exception handler. Listing 13 shows the results.
Listing 13A C++ program with an exception handler, called from Python.
Just before Python program invocation ExceptionManagement program invoked: ExceptionManagement result: Is NULL Standard exception: std::bad_alloc Is NULL Returning
In Listing 13, the C++ exception handler code has been invoked, and the program returns as normal. The result is a more controlled program that gives us a chance to clean up and exit gracefully.