With C++17 we got std::optional
which is a useful wrapper for expressing nullable types.
Can I use it for error handling? It's quite appealing to do so:
optional<int> Compute()
{
//... compute something valid...
return std::nullopt; // error!
}
Would it be a good choice? Isn't it the same are returning a null pointer?
The problem, that people reports, is that you lose a message what happened in the case of an error. So returning some status code might be better.
other alternatives:
std::variant<Value, errorCode>
std::pair<Value, errorCode
The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.
As a conclusion, std::optional is as efficient as a custom type to represent an optional integer value. Don't implement your own type, simply use the standard type.
The technique used in Optional for error handing is similar to the old one (in C or even go), returning error codes to handle exceptions. But instead of error code we return a generic type called Optional which indicates presence or absence of a value.
Exception handling in C++ is done using three keywords: try , catch and throw . To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing this portion of code in a try block. When an exception occurs within the try block, control is transferred to the exception handler.
I think std::optional
is a great replacement for error handling code like that:
int GetAvailablePositiveNumber()
{
if (condition)
return 1;
if (condition2);
return 2;
return -1;
}
int result = GetAvailablePositiveNumber();
if (result == -1)
{
// We have no available positive numbers - handle error;
}
You will never need to use -1 ever again.
Also about the other alternatives you have mentioned, my answer is: the right tool for the right job. They have their own uses. Just pick the best tool on a case-by-case basis.
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