I writing a Go program, in this program i am using cgo
to call a dynamic library (`.so) written in C++ to process a communication protocol. The code in that C++ library may throw exceptions, so I'm using try-catch to catch exceptions in the library code, and also using defer to catch these exception in my Go code when calling C++ function of a library.
But it turns out, Go code cannot catch exception when c++ try catch the exception.
My question is how to catch a C++ exception in Go code which called the throwing C++ function via cgo
.
No way to do that directly.
Create a C/C++ wrapper (you can write it "inline" in the cgo
-related "comment" in your Go source code) which would call the target C++ function, but would wrap the call in a try
/catch
block, catch everything (std::exception
) and turn any caught exception into a special value returned from the call.
Found a good explanation of how to do that, with examples.