Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use std::optional for error handling? [closed]

Tags:

c++

c++17

stl

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
  • return error code and have a value as an output parameter
  • throw an exception
like image 514
fen Avatar asked May 10 '18 06:05

fen


People also ask

What is std :: optional used for?

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.

Is STD optional efficient?

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.

What is optional error?

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.

How do you catch errors in C++?

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.


1 Answers

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.

like image 100
Zingam Avatar answered Sep 20 '22 21:09

Zingam