Best way to abstract wrapping C error handling with exceptions : <p>It is not uncommon for a useful C library to not provide C++ bindings. It's easy to call C from C++, but among other issues, a C++ project probably wants exceptions, rather than numerical error return values.</p>

<p>Is there any particular convention or trick for converting to exceptions without including an <code>if</code> and <code>throw</code> with each function call?</p>

<p>I wrote this solution for wrapping gphoto2 calls. Having to wrap the templated function in a macro is awkward (but the function name is kind of important for error messages; the logic here is similar to <code>perror</code>). </p>

<p>Is there a better technique, or any open source project that does this particularly well?</p>

<pre class="lang-cpp prettyprint-override"><code>#include &lt;gphoto2/gphoto2.h&gt;
#include &lt;string&gt;

class Gphoto2Error : public std::exception {
  private:
    std::string message;

  public:
    Gphoto2Error(std::string func, int err) {
        message = func + ": " + std::string(gp_result_as_string(err));
    }
    const char *what() const throw() {
        return message.c_str();
    }
};

template &lt;typename F, typename... Args&gt;
void _gpCall(const char *name, F f, Args... args) {
    int ret = f(args...);
    if (ret != GP_OK) {
        throw Gphoto2Error(name, ret);
    }
}
#define gpCall(f, ...) ((_gpCall(#f, ((f)), __VA_ARGS__)))

int main() {
    GPContext *ctx = gp_context_new();
    Camera *camera;
    gpCall(gp_camera_new, &amp;camera);
    gpCall(gp_camera_init, camera, ctx);
}
</code></pre>
