Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should we implement std::error_code compatible API?

Assuming we are writing a library and that we want to provide fine grain control over error and exceptions:

void foo();
void foo(std::error_code&);

Sould we implement foo() as throwing a std::system_error and let foo(std::error_code&) catch all exception and extract the error_code.

Or sould we implement foo(std::error_code&) as a never throwing function and throw a function in foo() depending on the presence of an error code?

like image 424
authchir Avatar asked Sep 15 '12 14:09

authchir


People also ask

Should I use C++ exceptions?

Exceptions are preferred in modern C++ for the following reasons: An exception forces calling code to recognize an error condition and handle it. Unhandled exceptions stop program execution. An exception jumps to the point in the call stack that can handle the error.

When to throw exceptions C++?

An exception should be thrown from a C++ constructor whenever an object cannot be properly constructed or initialized. Since there is no way to recover from failed object construction, an exception should be thrown in such cases.

Does throwing an exception stop execution C++?

throw usually causes the function to terminate immediately, so you even if you do put any code after it (inside the same block), it won't execute. This goes for both C++ and C#.

Are C++ exceptions bad?

Why are C++ exceptions so useless? The main reason C++ exceptions are so often forbidden is that it's very hard to write exception safe C++ code. Exception safety is not a term you hear very often, but basically means code that doesn't screw itself up too badly if the stack is unwound.


1 Answers

boost library works with exceptions and with boost::system::error_code, so, i think you can orientate on this library. For example boost::asio::basic_stream_socket::connect has two versions

void connect(
    const endpoint_type & peer_endpoint);

boost::system::system_error Thrown on failure.

boost::system::error_code connect(
    const endpoint_type & peer_endpoint,
    boost::system::error_code & ec);

ec Set to indicate what error occurred, if any.

But it depends on what foo does, i think too.

like image 165
ForEveR Avatar answered Oct 06 '22 01:10

ForEveR