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?
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.
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.
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#.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With